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/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/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..bfa3d6aa47 100644 --- a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java +++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java @@ -198,6 +198,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..7d5218d338 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; @@ -182,7 +183,7 @@ class DefaultTbAiService implements TbAiService { 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..c737630cf5 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 @@ -35,7 +35,7 @@ class DefaultAiChatService implements AiChatService { @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 +50,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( 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..7e6d1e8414 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 @@ -16,6 +16,7 @@ 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; @@ -36,7 +37,7 @@ public class DefaultAiSolutionService implements AiSolutionService { @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 @@ -80,6 +81,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 +107,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/TbAiPooledConnection.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java index 3b77aad205..d74fc3bf2b 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; 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/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/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..7cd8d8f3ba 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 @@ -64,12 +64,12 @@ class DefaultAiChatServiceTest { } @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 +77,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 +94,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 +113,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 +132,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 +149,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 @@ -211,9 +227,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..444325ab3e 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 @@ -71,10 +71,10 @@ class DefaultAiSolutionServiceTest { } @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 +82,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(); @@ -214,6 +214,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/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/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/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/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/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/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..8be5f1ffbb 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 @@ -309,6 +309,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..d0c29ff1e0 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 @@ -37,6 +37,7 @@ 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 +46,12 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { private static final Map alarmFieldColumnMap = new HashMap<>(); + 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 +140,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 +181,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()); @@ -180,7 +213,9 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { } sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)) .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 +236,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 +268,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 +278,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 +288,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 +329,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 +346,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..e4b49b155b 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 @@ -70,8 +70,10 @@ 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 +731,75 @@ 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()); + } + private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { return toQuery(pageLink, Collections.emptyList()); } diff --git a/pom.xml b/pom.xml index c86b141c3c..0bd1e5de9a 100755 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ /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 diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 18e0ec560f..638962740c 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", @@ -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/ui-ngx/package.json b/ui-ngx/package.json index c4b5930b13..522edcb042 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -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", @@ -105,8 +107,6 @@ "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" }, 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/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..645ab4a114 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)); } @@ -57,6 +62,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 +119,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/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..d31ddfe2b4 100644 --- a/ui-ngx/src/app/core/http/user-permissions.service.ts +++ b/ui-ngx/src/app/core/http/user-permissions.service.ts @@ -20,6 +20,7 @@ import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-uti import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; @Injectable({ providedIn: 'root' @@ -126,11 +127,16 @@ export class UserPermissionsService { 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/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..75c81dce74 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,6 +20,8 @@ export class NotificationMessage { verticalPosition?: NotificationVerticalPosition; panelClass?: string | string[]; modern?: boolean; + actionLabel?: string; + onAction?: () => void; } export class HideNotification { 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..c742ca7fb6 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,189 @@ 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); + 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 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 { + 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 +256,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,11 +267,50 @@ 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; @@ -190,6 +327,7 @@ export class AiAssistantPanelService implements OnDestroy { } else { this._lastChatIdByContext.delete(key); } + this.storeChats(); } lastChatIdForContext(): string | undefined { @@ -198,10 +336,12 @@ export class AiAssistantPanelService implements OnDestroy { } close(): void { + this._restored.set(false); this._open.set(false); } openPanel(): void { + this._restored.set(false); this._open.set(true); } @@ -212,6 +352,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 +371,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 +418,50 @@ 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; + } + } + emitUpdatedData(affectedEntities: Array): void { this._updatedData$.next(affectedEntities); } teardown(): void { + 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..d35116c93e --- /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): 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 (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..1cd795dcf0 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-slash.service.ts @@ -0,0 +1,73 @@ +// 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]')) { + 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..7a709f69cf --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-solutions.service.ts @@ -0,0 +1,253 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { 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 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(); + } + + setRunning(solutionId: string | undefined, running: boolean): void { + if (!solutionId || this._running().has(solutionId) === running) { + return; + } + if (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; + }); + } + + 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' : null; + } + return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null; + } + + 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, + 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..a72e72d026 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,17 +1576,14 @@ 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) ], + [ + MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable() + ], [ MenuId.device_all, (_authState, userPermissionsService) => userPermissionsService.hasReadGenericPermission(Resource.DEVICE) @@ -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..5e6b27768a --- /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.isAiAvailable(); + } + + 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/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..d08107aa5b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -0,0 +1,187 @@ + +@if (hood()) { +

{{ 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.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.label) { +
{{ say(block.label) }}
+ } +
+ @for (row of block.rows; track $index) { + {{ row.key }}{{ row.value }} + } +
+ } + @case ('series') { +
+ @for (row of block.rows; track row.key) { +
+ {{ row.key }} + + {{ 'ai-assistant.detail.series' | translate:{points: row.points, min: number(row.min), max: number(row.max), last: number(row.last)} }} +
+ } +
+ } + @case ('keys') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (key of block.keys; track $index) { + {{ key }} + } +
+ } + @case ('facts') { +
+ @for (fact of 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 ('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..12b1578b66 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts @@ -0,0 +1,271 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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) { + return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE'); + } + + 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 { + return 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); + } + + 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 => block.type === 'facts' && block.rows.forEach(fact => want(fact.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..c6377a8787 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -0,0 +1,2263 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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; +} + +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; + from: number; + to: number; + path: string; +} + +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}; +} + +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; rows: AiDetailValue[]} + | {type: 'series'; 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: 'text'; text: string} + | {type: 'json'; label: string; text: string} + | {type: 'images'; rows: AiDetailImage[]}; + +export interface AiDetailImage { + label?: AiDetailText; + url: string; +} + +export interface AiDetailView { + hood?: AiDetailText; + blocks: AiDetailBlock[]; +} + +export type AiDetailNames = ReadonlyMap; + +const K = 'ai-assistant.detail.'; + +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 Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000); + } + if (typeof value === 'string') { + const parsed = aiParse(value); + return parsed !== value ? aiValueText(parsed) : 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; +} + +export const aiHumanize = (key: string): string => { + const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase(); + return words ? words.charAt(0).toUpperCase() + words.slice(1) : key; +}; + +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 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 min = Math.min(...values); + const max = Math.max(...values); + const from = sorted[0][0]; + const to = sorted[sorted.length - 1][0]; + const width = 96; + const height = 20; + const span = to - from || 1; + const range = max - min || 1; + const path = sorted.map(([ts, value], index) => + `${index ? 'L' : 'M'}${((ts - from) / span * width).toFixed(1)} ${(height - 1 - (value - min) / range * (height - 2)).toFixed(1)}`).join(''); + return {key, points: sorted.length, min, max, last: sorted[sorted.length - 1][1], from, to, path}; +} + +function telemetry(result: Values): AiDetailBlock[] { + const latest: AiDetailValue[] = []; + const history: AiDetailSeries[] = []; + const other: AiDetailValue[] = []; + 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)) { + const numbers = data.map(point => [timeOf(point.ts), Number(point.value)] as [number, number]).filter(([ts, value]) => ts && Number.isFinite(value)); + if (numbers.length > 1) { + history.push(series(key, numbers)); + } else if (data.length) { + latest.push({key, value: aiValueText(data[0].value), time: timeOf(data[0].ts)}); + } + continue; + } + if (!isObject(data)) { + other.push({key, value: aiValueText(data)}); + continue; + } + const entries = Object.entries(data).filter(([ts]) => timeOf(ts)); + const numbers = entries.map(([ts, value]) => [timeOf(ts), Number(value)] as [number, number]).filter(([, value]) => Number.isFinite(value)); + if (entries.length > 1 && numbers.length === entries.length) { + history.push(series(key, numbers)); + } else if (entries.length) { + const [ts, value] = entries.sort((a, b) => Number(b[0]) - Number(a[0]))[0]; + latest.push({key, value: aiValueText(value), time: timeOf(ts)}); + } 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 alarmMeta(row: Values): string { + return [row.severity, row.status, timeOf(row.startTs) ? new Date(timeOf(row.startTs)).toLocaleString() : undefined] + .filter(Boolean).map(String).join(' · '); +} + +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, meta: alarmMeta(row), severity: str(row.severity)} : 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 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' && Array.isArray(filter.originatorIds) && filter.originatorIds.length === 1) { + key = 'search-alarms-of'; + params.entity = entity(filter.originatorIds[0], filter.originatorType, names); + } + 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: 'note', text: text('nothing-found')}); + } + continue; + } + const groupType = entityType === 'ENTITY_GROUP' ? str(filter.groupType)?.toUpperCase() : undefined; + const rows = 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}] : []; +} + +export function aiActionDetailView(action: AiAction, names: AiDetailNames): AiDetailView { + const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {}; + const result = 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', 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: new Date(result.sendsAt).toLocaleString()}); + } + 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 '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: new Date(read.createdTime).toLocaleString()}); + } + 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 hood = values.mode === 'HISTORY' || values.startTime + ? text(keys ? 'read-history-keys' : 'read-history', {entity: target, keys, from: dateText(values.startTime), to: endText(values.endTime)}) + : text(keys ? 'read-latest-keys' : 'read-latest', {entity: target, keys}); + const blocks = isObject(result) ? telemetry(result) : 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(', ')}); + } + const blocks: AiDetailBlock[] = [{type: 'facts', rows}]; + if (str(result.note)) { + blocks.push({type: 'text', text: result.note}); + } + return {hood: text('read-endpoints'), blocks}; + } + 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 '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: new Date(result.lastConnect).toLocaleString()}); + } + 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']); + 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}] : generic(result.note, 'result')}; + } + 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) ? new Date(event.time).toLocaleString() : 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) ? new Date(version.time).toLocaleString() : 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) ? new Date(log.time).toLocaleString() : 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; +} + +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()) ? date.toLocaleString([], {dateStyle: 'medium', timeStyle: 'short'}) : '—'; +} + +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 '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..1fd53e8632 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -0,0 +1,43 @@ + +@switch (action().status) { + @case ('RUNNING') { + + } + @case ('STOPPED') { + + } + @default { +
+ + @if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}}{{ chip.after }}} @else {{{ outcome() }}} + @if (duration()) { + {{ duration() }} + } +
+ @if (arrival()?.readings?.length) { +
+ @for (reading of arrival().readings; track reading.key) { + {{ reading.key }}{{ reading.value }} + } +
+ } + @if (listing(); as hub) { +
+ +
+ } + @if (hasDetails()) { + + @if (records().length) { + + } + + + } + } +} 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..7143edb765 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -0,0 +1,95 @@ +// 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); +} + +.out { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 2px; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + .mark { + flex: none; + display: flex; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + margin-top: 0; + color: var(--tb-ok); + } + + .say { + min-width: 0; + overflow-wrap: anywhere; + } + + .dur { + flex: none; + margin-left: auto; + font-family: var(--tb-mono); + font-size: 12px; + line-height: var(--chat-line-lh); + color: var(--k-faint); + white-space: nowrap; + } +} + +:host(.fail) .out .mark { + color: var(--tb-crit); +} + +.action-details { + display: block; + margin: 4px 0 0 28px; + + ::ng-deep .tb-disc.tb-disc-details { + margin: 0; + + > summary { + color: var(--tb-ink-76); + } + } + + .records { + display: block; + margin: 8px 0 4px; + } +} + +.k-arrived { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + margin: 4px 0 0 28px; + 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); + } +} 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..5806e07216 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, 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 { aiActionDetailView, AiDetailFact, AiDetailNames, aiParse } from '@home/components/ai/ai-action-detail.models'; +import { + AiAction, + aiConnectionCheckOf, + aiEntityKind, + aiActionDuration, + aiActionText, + aiActionWords +} 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 = action.tool === 'install_iot_hub_item' && 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); + + outcomeText = input(); + + autoApproved = input(false); + + linkEntity = input(true); + + outcomeChip = computed(() => { + 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'; + } + + private 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 words = this.outcomeWords(); + return this.autoApproved() ? this.translate.instant('ai-assistant.action.auto-approved', {words}) : words; + }); + + 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.reason(action.result) ?? this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); + } + const words = this.words(); + return aiActionText(this.translate, words, 'done'); + } + + duration = computed(() => this.action().durationMs != null ? aiActionDuration(this.translate, this.action().durationMs) : ''); + + names = input(new Map()); + + facts = input([]); + + detail = computed(() => { + const view = aiActionDetailView(this.action(), this.names()); + const facts = this.facts(); + const reason = this.action().status === 'FAILURE' && this.outcomeText() && !view.blocks.length ? this.reason(this.action().result) : undefined; + const blocks = [...view.blocks, ...(reason ? [{type: 'text' as const, text: reason}] : []), ...(facts.length ? [{type: 'facts' as const, rows: facts}] : [])]; + return {...view, blocks}; + }); + + records = computed(() => this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []); + + hasDetails = computed(() => !!this.detail().hood || !!this.detail().blocks.length || !!this.records().length); + + 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..a5e8c87c3d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -0,0 +1,817 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { TranslateService } from '@ngx-translate/core'; + +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: 'read-attributes', + 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', + 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', + list_installed_iot_hub_items: 'list-installed-iot-hub-items', + install_iot_hub_item: 'install-iot-hub-item', + 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-connection-settings', + 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' +}; + +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); + +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 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; + quiet?: string; + test?: AiHandOverTest; + paste?: {label: string; icon: string; intro: string}; +} + +export interface AiHandOverTest { + hint?: string; + commands: {os: 'macos' | 'windows' | 'linux'; command: string}[]; + outcomes: {output: string; meaning: string; ok: boolean}[]; + 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; + } + const outcomes = (Array.isArray(value.outcomes) ? value.outcomes : []) + .filter(item => text(item?.output) && text(item?.meaning)) + .slice(0, 4) + .map(item => ({output: text(item.output), meaning: text(item.meaning), ok: item.ok === true})); + 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, outcomes, ...(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, quiet: text(values.quiet), + 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 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 function aiQuestionsOf(args: unknown): 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: question.question.trim(), + why: typeof question.why === 'string' ? question.why : undefined, + options: (Array.isArray(question.options) ? question.options : []) + .filter(option => typeof option?.label === 'string' && option.label.trim()) + .slice(0, 6) + .map(option => ({label: option.label.trim(), hint: typeof option.hint === 'string' ? option.hint : 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 + })); +} + +const MAX_PROMPTS = 4; + +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.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; + 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'; + +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'}, + SOLUTION_TEMPLATE: {icon: 'dashboard_customize', palette: 'solution'}, + DEVICE_PROFILE: {icon: 'category', palette: 'device'}, + ASSET: {icon: 'domain', palette: 'device'}, + ASSET_PROFILE: {icon: 'category', palette: 'device'}, + INTEGRATION: {icon: 'input', palette: 'path'}, + CONVERTER: {icon: 'transform', palette: 'path'}, + CALCULATED_FIELD: {icon: 'functions', palette: 'path'}, + RULE_CHAIN: {icon: 'account_tree', palette: 'chain'}, + EDGE_RULE_CHAIN: {icon: 'account_tree', palette: 'chain'}, + AGENT: {icon: 'memory', palette: 'device'}, + AGENT_APPLICATION: {icon: 'apps', palette: 'device'}, + AGENT_PROFILE: {icon: 'badge', palette: 'device'}, + AGENT_APP_PROFILE: {icon: 'inventory_2', palette: 'device'}, + IOT_HUB: {icon: 'hub', palette: 'solution'}, + ALARM_RULE: {icon: 'rule', palette: 'rule'}, + ALARM: {icon: 'notification_important', palette: 'rule'}, + NOTIFICATION_RULE: {icon: 'notifications_active', palette: 'rule'}, + NOTIFICATION_TEMPLATE: {icon: 'description', palette: 'path'}, + NOTIFICATION_TARGET: {icon: 'group', palette: 'people'}, + DASHBOARD: {icon: 'dashboard', palette: 'view'}, + DASHBOARD_WIDGET: {icon: 'widgets', palette: 'view'}, + DASHBOARD_STATE: {icon: 'tab', palette: 'view'}, + DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'}, + WIDGET_TYPE: {icon: 'widgets', palette: 'view'}, + WIDGETS_BUNDLE: {icon: 'now_widgets', palette: 'view'}, + OTA_PACKAGE: {icon: 'system_update', palette: 'device'}, + MAIL_TEMPLATE: {icon: 'mail', palette: 'view'}, + CUSTOM_TRANSLATION: {icon: 'translate', palette: 'view'}, + CUSTOM_MENU: {icon: 'menu', palette: 'view'}, + MOBILE_APP: {icon: 'smartphone', palette: 'device'}, + MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'device'}, + MOBILE_QR_CODE: {icon: 'qr_code_2', palette: 'device'}, + SCHEDULER_EVENT: {icon: 'schedule', palette: 'rule'}, + REPORT_TEMPLATE: {icon: 'description', 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: 'event_repeat', palette: 'rule'}, + REPORT: {icon: 'summarize', palette: 'view'}, + TWO_FACTOR_SETTINGS: {icon: 'phonelink_lock', palette: 'people'}, + DOMAIN: {icon: 'language', palette: 'people'}, + MY_PROFILE: {icon: 'account_circle', palette: 'people'}, + MY_TWO_FACTOR: {icon: 'phonelink_lock', palette: 'people'}, + API_KEY: {icon: 'vpn_key', palette: 'people'}, + MAIL_SERVER: {icon: 'outgoing_mail', palette: 'view'}, + IMAGE: {icon: 'image', palette: 'view'}, + TB_RESOURCE: {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'}, + ENTITY_GROUP: {icon: 'folder_shared', palette: 'people'}, + ROLE: {icon: 'admin_panel_settings', palette: 'people'}, + GROUP_PERMISSION: {icon: 'key', palette: 'people'} +}; + +export function aiEntityKind(entityType: string, alarmRule = false): AiEntityKind { + return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'solution'}; +} 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..020db48d8b 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,122 @@ 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) }} -
+ @switch (state) { + @case ('pending') { + @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.image || change.currentImage) { + + + } @else { + + + } + + } + + @if (unchanged.length && showUnchanged) { + + @for (same of unchanged; track $index) { + + + + + } + + } +
{{ 'ai-assistant.review.current' | translate }}{{ 'ai-assistant.review.new' | translate }}
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} } + @if (change.currentImage) { } @else { {{ change.current }} } + + @if (change.image) { } @else { {{ change.value }} } + {{ change.current }}{{ change.value }}
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }{{ same.value }}
+ @if (unchanged.length) { + + } + } +
+ + +
+ @if (denying) { +
+ +
+ } + } + @case ('denied') { +

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

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

{{ 'ai-assistant.review.expired-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) { + } +
} 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..69aabaf19d 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,32 +1,167 @@ // 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 } 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' | 'approved' | 'auto' | 'denied' | 'expired'; + +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 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 REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync']); + +const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol']); + +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 STACK_AT = 24; +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]); @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; @@ -34,66 +169,316 @@ export class AiApprovalCardComponent implements OnChanges { @Input() autoApprove = false; + @Input() answered = false; + + @ViewChild('denyInput') denyInput: ElementRef; + @Output() approvalAction = new EventEmitter(); - @HostBinding('class') state: ApprovalCardState = 'pending'; + @Output() askAgain = 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.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 = 'expired'; + } 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(), + 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'; + case 'expired': + return 'timer_off'; default: - return 'error_outline'; + return 'rate_review'; } } - approve(): void { - this.emitApproval(); + get headText(): string { + return this.translate.instant('ai-assistant.review.head.' + this.state); + } + + 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 = this.data?.tool === 'install_iot_hub_item' ? (this.data.arguments as {versionId?: unknown})?.versionId : null; + return typeof id === 'string' && id ? id : null; } - approveAll(): void { - this.emitApproval(true); + get approveLabel(): string { + if (this.hubVersionId) { + return 'ai-assistant.record.install'; + } + if (this.review?.verb && REVIEW_VERBS.has(this.review.verb)) { + return 'ai-assistant.review.verb.' + this.review.verb; + } + if (this.isDestructive) { + return 'ai-assistant.review.delete'; + } + switch (this.review?.change) { + case 'CREATE': + return 'ai-assistant.review.create'; + case 'UPDATE': + return 'ai-assistant.review.update'; + default: + return 'ai-assistant.approve'; + } + } + + get recordName(): string { + const name = this.review?.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, images: {current: row.currentImage ? row.current : undefined, value: row.image ? row.value : undefined}} + : {label: row.label, raw: true, value: `${row.current ?? '—'} → ${row.value}`, mono: row.valueCode}) + ]; + } + + get stackedDiff(): boolean { + return this.changes.some(change => !change.image && !change.currentImage + && ((change.current?.length ?? 0) > STACK_AT || (change.value?.length ?? 0) > STACK_AT)); + } + + 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 === 'expired'; + } + + toggleUnchanged(): void { + this.showUnchanged = !this.showUnchanged; + if (this.showUnchanged) { + aiRevealOpened(this.host.nativeElement); + } + } + + approve(): void { + this.state = this.autoApproved ? 'auto' : 'approved'; + this.denying = false; + 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(); + this.denying = false; + this.state = 'denied'; + this.approvalAction.emit(reason + ? {executionId: this.data.executionId, approved: false, reason} + : {executionId: this.data.executionId, approved: false}); } - private emitApproval(autoApprove = false): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: true, autoApprove}); + 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 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 { + if (OWN_TYPE_LABELS.has(entityType)) { + return this.translate.instant('ai-assistant.review.type.' + entityType); + } + const translation = entityTypeTranslations.get(entityType as EntityType)?.type; + return translation ? this.translate.instant(translation) : 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..fff54110b0 --- /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..89d1dde9df --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AfterViewInit, Component, ElementRef, EventEmitter, inject, input, Output, signal, ViewChild } from '@angular/core'; + +const PANE_MIN = 360; +const CHAT_MIN = 340; +const WIDTH_KEY = 'tbSolutionPaneWidth'; + +@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)' + } +}) +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); + + ngAfterViewInit(): void { + setTimeout(() => this.refreshEdges(), 50); + } + + 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(); + } + + 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..7376bd7717 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts @@ -0,0 +1,253 @@ +// 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).isAiAvailable(); + + 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(); + } + }); + }); + + constructor() { + if (this.available) { + this.chats.watchStatus(); + } + 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..cfa5fb1bb8 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,92 @@ @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; - } - } - - // <= 599px: full-screen panel, the card fills the whole width. - @media #{$mat-xs} { - width: 100%; - - .ai-assistant-container { - margin: 0; - width: auto; - - &.fill { - width: auto; - } - - &.details-open { - padding: 8px; - } - } } -} -:host::ng-deep { - .ai-assistant-header { - .chat-selector { - .mdc-button__label { - width: 100%; - text-align: start; - text-overflow: ellipsis; - overflow: hidden; - } - } + .ai-assistant-chat { + flex: 1; + min-height: 0; } -} - -::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; - } - } + @media (max-width: 1100px) { + top: auto; + left: 0; + width: auto; + height: clamp(min(340px, 70vh), 50vh, 600px); + transform: translateY(100%); - .ai-chat-action-menu { - .delete { - --mat-menu-item-icon-color: #FF5722; - --mat-menu-item-label-text-color: #FF5722; + &.open { + transform: translateY(0); + box-shadow: 0 -1px 0 rgba(16, 24, 40, 0.06), 0 -12px 32px rgba(16, 24, 40, 0.08); } } } 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..24594b0052 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,12 @@ // 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 { 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 +15,290 @@ 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()' } }) -export class AiAssistantPanelComponent implements OnInit { +export class AiAssistantPanelComponent { panelService = inject(AiAssistantPanelService); - @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatComponent) chat: AiChatComponent; + + @ViewChild('gripTip', {read: MatTooltip}) gripTip: MatTooltip; + + private zone = inject(NgZone); + + private static readonly PAGE_REFLOW_MS = 50; + + resizing = signal(false); get isOpen() { return this.panelService.open(); } - slideDone = signal(false); + readonly defaultWidth = 364; - loading = signal(false); + readonly minWidth = 320; - isCreatingNew = signal(false); + readonly maxWidth = 480; - messages = signal([]); + 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; - completedExecutions = signal>({}); + width = signal(this.defaultWidth); - chatId = signal(undefined); + room = signal(0); - subTitle = computed(() => { - return this.panelService.config()?.subTitle ?? this.translate.instant('ai-assistant.sub-title'); + splitWidth = computed(() => { + const room = this.room(); + return Math.min(AiAssistantPanelComponent.SPLIT_MAX, Math.floor(room / 2), room - AiAssistantPanelComponent.PAGE_MIN); }); - 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 ?? ''; - }); + splitAvailable = computed(() => this.room() > 0 && window.innerWidth > AiAssistantPanelComponent.SHEET_MAX_WINDOW + && this.splitWidth() >= AiAssistantPanelComponent.SPLIT_MIN); - promptExamples = computed(() => this.panelService.config()?.promptExamples ?? []); + split = computed(() => this.width() > this.maxWidth); - autoApprove = computed(() => this.panelService.isAutoApprove(this.chatId())); + private wanted = this.defaultWidth; - selectedChatTitle = computed(() => { - const id = this.chatId(); - if (!id) return null; - return (this.panelService.chats() ?? []).find(c => c.id === id)?.title ?? null; - }); + private panelWidth = 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); - } - } + chatId = signal(undefined); - return groups.filter(g => g.chats.length > 0); - }); + private context = inject(AiAssistantContextService); + + clientContext = this.context.clientContext; + + welcome = this.context.welcome; - 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 chats = inject(AiChatsService); private elementRef = inject(ElementRef); - private loadChat$ = new Subject(); - private cancelMessage$ = new Subject(); - private sessionAffectedEntities: EntityId[] = []; - private messageCancelled = false; - private resumeOnOpen = false; + private static readonly WIDTH_KEY = 'tbAiPanelWidth'; - private static readonly RESUME_ATTEMPTS = 4; - private static readonly RESUME_DELAY_MS = 2000; + private static readonly APPLIED_WIDTH_KEY = 'tb-ai-panel-applied-width'; + + private lastContextKey: string | null = null; + + 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')); + }); 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(); + untracked(() => { + 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 lastContextKey: string | null = null; - - // 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(); + untracked(() => { + const carried = this.panelService.takeCarriedChat(); + if (carried && carried === this.chatId()) { + return; + } + this.chatId.set(undefined); + this.selectLastChat(); + }); } this.lastContextKey = key; }); - 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()); - }); - } - - close(): void { - this.panelService.close(); - } - - // 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; + 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; } - this.slideDone.set(true); - this.promptInput?.focus(); - } - - onApprovalAction(event: ApprovalResult): void { - const chatId = this.chatId(); - if (event.autoApprove && chatId) { - this.panelService.setAutoApprove(chatId, true); + if (applied) { + this.width.set(applied); + document.documentElement.style.setProperty('--tb-ai-panel-w', applied + 'px'); } - this.aiChat.resolveToolApproval( - {executionId: event.executionId, approved: event.approved}, - {ignoreLoading: true, ignoreErrors: true} - ).subscribe(); - } - - setMenuWidth(triggerEl: MatButton): void { - const width = triggerEl._elementRef.nativeElement.offsetWidth; - document.documentElement.style.setProperty('--chat-menu-dynamic-width', `${width}px`); + setTimeout(() => this.fit()); } - 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); + fit(): void { + this.room.set(this.elementRef.nativeElement.parentElement?.clientWidth ?? window.innerWidth); + this.show(this.wanted); } - useExample(example: AiAssistantPromptExample): void { - this.promptInput?.setValue(example.message); - } - - 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); - } - } - }); + toggleSplit(): void { + if (this.split()) { + this.setWidth(this.panelWidth, true); + } else if (this.splitAvailable()) { + this.panelWidth = this.width(); + this.setWidth(this.splitWidth(), true); + } } - reset(createNew?: boolean): void { - this.cancelActiveMessage(); - this.isCreatingNew.set(!!createNew); - this.chatId.set(undefined); - this.messages.set([]); + private widest(): number { + return this.splitAvailable() ? this.splitWidth() : Math.min(this.maxWidth, Math.max(this.minWidth, Math.round(this.room() / 2) || this.maxWidth)); } - private cancelActiveMessage(): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.stopLoadingState(); - this.promptInput?.reset(); + 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; + } + return value; } - // 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(); + 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)); + } } - private dropChatFromOtherContext(): void { - const chatId = this.chatId(); - if (chatId && chatId !== this.panelService.lastChatIdForContext()) { - this.reset(); + 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); } } - 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') + 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 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))); } - }).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); - } + }; + grip.setPointerCapture(event.pointerId); + document.body.classList.add('tb-ai-resizing'); + this.zone.runOutsideAngular(() => { + const move = (e: PointerEvent) => { + current = Math.round(Math.min(widest, Math.max(this.minWidth, startWidth + (startX - e.clientX)))); + if (!frame) { + frame = requestAnimationFrame(paint); + } + }; + 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.style.width = ''; + this.zone.run(() => { + this.resizing.set(false); + this.setWidth(current, current !== startWidth); }); - } + }; + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up); + grip.addEventListener('pointercancel', up); }); } - 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(); - }); - } - }); + close(): void { + this.panelService.close(); } - private loadChats(): void { - const chats = this.panelService.chats(); - if (chats !== null) { - this.selectLastChat(chats); + 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.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).subscribe(chats => { - this.panelService.setChats(chats); - this.selectLastChat(chats); - }); + this.panelService.carryChat(chatId); } - 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); - } - } + onChatId(chatId: string | undefined): void { + this.chatId.set(chatId); + this.panelService.setLastChatId(chatId); } - private sendMessage(prompt: AiPromptMessage): Observable { - this.initLoadingState(); - this.sessionAffectedEntities = []; - this.messageCancelled = false; - - 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); + onSlideEnd(event: TransitionEvent): void { + if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { + return; } - - 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()) - ); + this.chat?.focus(); } - private resolveClientContextToSend(): AiChatClientContext | undefined { - const currentContext = this.panelService.clientContext(); - if (!currentContext) { - return undefined; - } + private dropChatFromOtherContext(): void { const chatId = this.chatId(); - const alreadySent = chatId ? this.panelService.getSentClientContext(chatId) : undefined; - return (!chatId || !isEqual(currentContext, alreadySent)) ? currentContext : undefined; - } - - 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; - } + if (chatId && chatId !== this.panelService.lastChatIdForContext()) { + this.chatId.set(undefined); } - 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) { + private selectLastChat(): void { + if (this.chatId()) { return; } - 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); - } - 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); - } - return of(chatMsg); + const carried = this.panelService.takeCarriedChat(); + if (carried && this.chats.find(carried)) { + this.chatId.set(carried); + return; } - } - - private handleChatTitleGenerated(chatMsg: ChatTitleGeneratedEvent): void { - const chatId = this.chatId(); - const title = chatMsg.data.title; - if (!chatId || !title) return; - this.panelService.updateChatTitle(chatId, title); - } - - private handleToolApproval(chatMsg: ToolExecutionRequestedEvent): Observable { - if (!chatMsg.data.needsApproval) { - return of(chatMsg); + const lastId = this.panelService.lastChatIdForContext(); + if (lastId && this.chats.find(lastId)) { + this.chatId.set(lastId); } - this.messages.update(list => [...list, {from: 'APPROVAL', data: chatMsg.data}]); - return of(chatMsg); - } - - private initLoadingState(): void { - this.loading.set(true); - } - - private stopLoadingState(): void { - this.loading.set(false); - } - - 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 showErrorToast(message: string): void { - this.store.dispatch(new ActionNotificationShow({ - message, - target: 'aiAssistant', - modern: true, - type: 'error', - verticalPosition: 'bottom', - horizontalPosition: 'center' - })); } } 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-card-actions.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts new file mode 100644 index 0000000000..9b71eda0a9 --- /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..e406abc2f6 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,44 +5,284 @@ --> @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]; 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) && (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]" + (approvalAction)="approval($event)" + (askAgain)="askAgain.emit()"> - } @else if (msg.status === 'INCOMPLETE') { -
+ } @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') { +
warning_amber - {{ msg.content }} + {{ msg.status === 'STOPPED' ? stoppedText($index, msg.content) : msg.content }}
+ @if (summaries[$index]; as entities) { + + } + @if (msg.status === 'STOPPED' && $last && !loading) { + + } } @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 (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..758bb07ea5 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,328 @@ // 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); } } - .incomplete { - padding: 10px 14px; + .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; + } + } + + .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; + } + + .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); + } + + .incomplete { + align-items: center; + gap: 10px; + padding: 8px 8px 8px 12px; + border-radius: 10px; + font-size: 13.5px; + line-height: 19px; + color: var(--tb-ink-76); + background: var(--tb-caution-tint); .incomplete-icon { flex: none; - color: #FF9800; - font-size: 20px; - width: 20px; - height: 20px; + color: var(--tb-caution); + font-size: 18px; + width: 18px; + height: 18px; } } + .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 +333,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,27 +355,301 @@ } - &::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); } - h5, h6 { - font-size: 18px; + ul, ol { + margin: 0; + padding-left: 24px; + padding-right: 0; + color: var(--tb-ink); } - a { + > p + ul, > p + ol { + margin-top: 6px; + } + + 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.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: 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; + } + } + } +} + +.action-ways { + margin: 8px 0 4px 28px; } 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..a17001873c 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,470 @@ // 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 { 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 { 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, + isHiddenAiAction, + isKitCardTool, + 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']; @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() 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() askAgain = new EventEmitter(); + @Output() editMessage = new EventEmitter(); + @Output() resume = 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; + + 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) {} + + 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.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.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; if (changes.messages.firstChange) { - setTimeout(() => this.scrollToLastUserMessage(), 0); + if (this.initialScroll === 'bottom') { + this.pinToBottom(); + } else { + setTimeout(() => this.scrollToLastUserMessage(), 0); + } return; } const wasNearBottom = this.isNearBottom(); @@ -52,7 +475,7 @@ export class AiChatMessagesComponent implements OnChanges { // 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; + this.waitApproval = lastMsg?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(lastMsg as ApprovalChatMessage); if (this.autoApprove) { setTimeout(() => this.scrollToBottom('auto'), 0); } else if (lastMsg?.from === 'USER') { @@ -63,6 +486,12 @@ 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) { + setTimeout(() => this.revealLastApproval(), 0); } else if (lastMsg?.from === 'APPROVAL') { if (prevLastMsg?.from === 'USER') { setTimeout(() => this.scrollToLastUserMessage(), 0); @@ -73,27 +502,549 @@ 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(this.translate.currentLang?.replace('_', '-') || undefined, 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; + } + + 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)); + } + + get retryPrompt(): string { + return this.translate.instant('ai-assistant.action.try-again-prompt'); + } + + 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') { + 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); + 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(); + } + } + + 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') { + 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) { + plans[index] = {steps, progress: null, gate: false}; + 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 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); + } 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; + } + + ngOnDestroy(): void { + 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)}); + } + + 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 { const userMessages = this.elementRef.nativeElement.querySelectorAll('.user'); if (userMessages.length) { - userMessages[userMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + userMessages[userMessages.length - 1].scrollIntoView({block: 'start', behavior: this.motion('smooth')}); } } private scrollToLastAiMessage(): void { const aiMessages = this.elementRef.nativeElement.querySelectorAll('.ai'); if (aiMessages.length) { - aiMessages[aiMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + aiMessages[aiMessages.length - 1].scrollIntoView({block: 'start', behavior: this.motion('smooth')}); } } @@ -115,12 +1066,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..01d3972043 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html @@ -0,0 +1,49 @@ + +@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..38fb599898 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss @@ -0,0 +1,144 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './ai-icon-button' 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; +} 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..c0f8901ad9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, 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); + + 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..6022e31a11 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -0,0 +1,480 @@ + +
+
+
+ + @if (variant() === 'panel') { + + } + +
+ @if (chatFiles().length && !titleRef?.renaming()) { + + } + @if (variant() === 'panel') { + @if (!titleRef?.renaming()) { + + + @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 }} +
+ } + + +
+ @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 (chat()) { + + + } + @if (docked() && (split() || splitAvailable())) { + + } + @if (recentChats().length) { +
{{ 'ai-assistant.recent-chats' | translate }}
+ @for (other of recentChats(); track other.id) { + + } + } + + @if (chat()) { + + } +
+ + + + + + + + +
{{ '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..72fd4f050f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -0,0 +1,792 @@ +// 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; + 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..4e971408b9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -0,0 +1,1524 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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 { ActionChatMessage, AiStartedFrom, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { + AiAssistantPromptExample, + AiChatClientContext, + AiPlatformLimit, + AiLinesQuote, + AiNotice, + AiPromptMessage, + aiQuoteText, + ChatInfo, + ChatLevel, + ApprovalResult, + ChatEvent, + SendChatMessageRequest, + 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 } from '@home/components/ai/ai-action.models'; +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 } from '@shared/models/ai-chat.models'; +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; +} + +@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()' + } +}) +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 RECENT_CHATS = 5; + + @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} + ]; + + recentChats = computed(() => this.chats.chats() + .filter(chat => chat.id !== this.chatId()) + .sort((a, b) => b.createdTime - a.createdTime) + .slice(0, AiChatComponent.RECENT_CHATS)); + + 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>({}); + + 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 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'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + 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()); + + 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(); + 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; + } + } + 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); + 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 chatIdEffect = effect(() => { + const chatId = this.chatId(); + untracked(() => { + if (this.fileChat !== chatId) { + this.shownFile.set(null); + this.fileOpen.set(false); + } + this.unlisting.set(null); + 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 { + 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()); + } + + composeText(text: string): void { + 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: file.name}), 'success'); + } + + onFileDiscarded(file: AiFile): void { + this.showToast(this.translate.instant('ai-assistant.file.discarded', {name: 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)); + } + + onAskAgain(): void { + if (!this.loading()) { + this.sendMsgFromUser({message: this.translate.instant('ai-assistant.review.ask-again-message'), resources: []}); + } + } + + 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; + } + this.sendMessage(prompt).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + 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.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.sendMsgFromUser({message: this.translate.instant('ai-assistant.resume'), resources: []}); + } + + 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); + }), + 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; + if (prompt.secrets) { + request.secrets = prompt.secrets; + } + const editorDraft = this.panelService.editorDraft(); + if (editorDraft) { + request.editorDraft = editorDraft; + } + return request; + } + + private sendMessage(prompt: AiPromptMessage): Observable { + this.messageCancelled = false; + const startOrContinue$ = this.chatId() + ? of(null) + : this.chats.create('New chat', this.newChatAutoApprove()).pipe( + tap(chat => { + this.freshChatId = chat.id; + this.shownChatId = chat.id; + this.chatId.set(chat.id); + }) + ); + const request = this.chatRequest(prompt); + 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)), + 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): 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': + this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data})); + if (event.data.executionStatus === 'SUCCESS') { + 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) { + 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) { + this.restoreLastPrompt(); + if (event.data.code === 'CREDITS_USED_UP') { + 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); + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', 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)) { + return; + } + const action: AiAction = { + executionId: started.executionId, + tool: started.tool, + arguments: started.arguments, + status: isKitCardTool(started.tool) ? 'SUCCESS' : 'RUNNING', + startedAt: started.startedAt ?? Date.now() + }; + 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}} : message)); + return true; + } + + private thinkingHeadline(data: {headline?: string; tool?: string; arguments?: unknown} | undefined): string | undefined { + if (data?.tool) { + return aiActionText(this.translate, aiActionWords(data.tool, data.arguments), 'run'); + } + return data?.headline; + } + + 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 { + 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 handleToolApproval(event: ToolExecutionRequestedEvent): void { + if (event.data.needsApproval) { + 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 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..daee69aa06 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -0,0 +1,938 @@ +// 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 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 && 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-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..aba2c626b3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts @@ -0,0 +1,44 @@ +// 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 { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; +import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; + +@NgModule({ + declarations: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiLoadingModalComponent, + AiNoTelemetryModalComponent + ], + imports: [ + CommonModule, + SharedModule + ], + exports: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiLoadingModalComponent, + AiNoTelemetryModalComponent + ] +}) +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..7fb233ca15 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,81 @@ // 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); +.cred { + display: inline-flex; + align-items: center; + gap: 8px; +} - &.WARNING { - --_donut-color: var(--tb-warning); - --_donut-track: color-mix(in srgb, var(--tb-warning) 20%, transparent); - } +.cred-line { + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; +} - &.DISABLED { - --_donut-color: var(--tb-crit); - --_donut-track: color-mix(in srgb, var(--tb-crit) 20%, transparent); - } - } +.cred.near .cred-line { + color: var(--tb-caution-text); +} - .ai-credits-donut { - &:hover { - background-color: rgba(0, 0, 0, 0.04); - } +.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; - &:focus-visible { - outline: 2px solid var(--tb-primary-500, #00695c); - outline-offset: 2px; - } + &:hover, &[aria-describedby] { + background: rgba(0, 0, 0, 0.05); + } - .donut-spinner { - width: 30px; - } + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } - .donut-title { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - } + svg { + display: block; + width: 20px; + height: 20px; + } - .donut-usage { - font-size: 13px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } + circle { + fill: none; + stroke-width: 2.5; } - .update-btn { - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.12); - --mat-button-outlined-horizontal-padding: 12px; + .track { + stroke: rgba(0, 0, 0, 0.1); + } + + .arc { + stroke: var(--ai-teal-500); + stroke-linecap: round; } } -:host ::ng-deep .mat-mdc-progress-spinner { - --mat-progress-spinner-active-indicator-color: var(--_donut-color); +.cred.near .arc { + stroke: var(--tb-caution); +} - .mdc-circular-progress__determinate-circle { - stroke-linecap: round; +.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..d86504ea90 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 @@ -6,15 +6,11 @@ import { AiLoadingModalComponent, AiLoadingModalData } from '@home/components/ai 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 { 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 { MatDialog } from '@angular/material/dialog'; @@ -68,7 +64,6 @@ export class AiDashboardGenerationService { }); } - generate(deviceId: string, destroyRef?: DestroyRef, timeseriesKeys: string[] = []): void { const dialogRef = this.dialog.open(AiLoadingModalComponent, { disableClose: true, @@ -98,9 +93,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-disclosure.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts new file mode 100644 index 0000000000..c9dd54eadf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, signal } 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; + } +} + +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<'details' | 'section' | 'divided'>('section'); + + key = input(''); + + private host = inject(ElementRef); + + private toggledOpen = signal(null); + + open = computed(() => this.toggledOpen() ?? aiDisclosureRemembered(this.key())); + + classes = computed(() => 'tb-disc ' + (this.variant() === 'details' ? 'tb-disc-details' + : this.variant() === 'divided' ? 'tb-disc-section tb-disc-divided' : 'tb-disc-section')); + + toggled(open: boolean): void { + if (open !== this.open()) { + this.toggledOpen.set(open); + aiDisclosureRemember(this.key(), open); + if (open) { + 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..42a7b1ca85 --- /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..9986a409e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -0,0 +1,183 @@ + +
+ @if (folded()) { +
+ {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} +
+ +

{{ 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().test; as test) { + + @if (test.hint) { +

{{ test.hint }}

+ } +
+ @if (test.outcomes.length) { + + + @for (outcome of test.outcomes; track $index) { + + + + + } +
{{ outcome.output }}{{ outcome.meaning }}
+
+ } +
+ } + @if (quiet() || stoppedQuiet()) { +
+
+ + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }} + @if (waiting()) { + {{ clock() }} + } +
+ @if (handOver().quiet && !undecoded()) { +

{{ handOver().quiet }}

+ } +
+ @if (canSendTest() && waiting()) { + + } + + @if (handOver().paste; as paste) { + + } @else { + + } +
+
+ } @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..87803444ad --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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 { 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; + +@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()); + + @Output() prompt = new EventEmitter(); + + @Output() stop = new EventEmitter(); + @Output() compose = new EventEmitter(); + @Output() openFile = 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()); + readonly open = signal(false); + readonly testState = signal<'idle' | 'sending' | 'sent' | 'failed'>('idle'); + readonly testAt = signal(0); + readonly testError = signal(''); + + 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 quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs()); + readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000))); + readonly undecoded = computed(() => this.wait()?.check?.failedStep === 'decoded'); + readonly stoppedQuiet = computed(() => { + const wait = this.wait(); + return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; + }); + + 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(() => { + 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()); + } + + 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); + } + + 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..86ade52c20 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -0,0 +1,47 @@ + +@let current = view(); + 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..e966ca6c88 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts @@ -0,0 +1,176 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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; + text: string; + action: LimitAction; + usage: boolean; + 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())); + + 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 viewOf(limit: AiPlatformLimit): LimitView { + const tenantAdmin = this.user?.authority === Authority.TENANT_ADMIN; + const sysAdmin = this.user?.authority === Authority.SYS_ADMIN; + const customer = this.user?.authority === Authority.CUSTOMER_USER; + 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)}), + text: customer + ? this.say('tenant-text-plain', {entities: this.entities(entityType).toLowerCase()}) + : this.say('tenant-text', {limit: limit.limit, entities: this.entities(entityType).toLowerCase()}), + action: 'request', + usage: tenantAdmin, + 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)}), + text: oldLicense + ? this.say('license-text-old', {entities: this.entities(licensedType).toLowerCase()}) + : this.say('license-text', {entities: this.entities(licensedType).toLowerCase()}), + action: oldLicense ? 'pricing' : (sysAdmin ? 'license' : 'request'), + usage: false, + 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}`)})), + text: this.say(addon === AddonType.WHITE_LABELING ? 'white-labeling-text' : 'pack-text'), + action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'), + usage: false, + 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'), + text: limit.message ?? '', + action: sysAdmin ? 'license' : 'none', + usage: false, + 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.scss b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss index 7af33d5f19..b0786e00db 100644 --- 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 @@ -1,10 +1,5 @@ // 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 { 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-plan.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html new file mode 100644 index 0000000000..93d741ce42 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html @@ -0,0 +1,57 @@ + +
+
+ {{ '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 (marks()[$index] === 'done') { + + } @else if (marks()[$index] === 'off') { + + } + + } + @if (step.by === 'user') {{{ 'ai-assistant.plan.you' | translate }}@if (step.needs) {{{ 'ai-assistant.plan.needs.' + step.needs | translate }}}}@for (part of parts(step.text); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}} +
  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..7b4d336115 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts @@ -0,0 +1,90 @@ +// 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 { decorateReferences } from '@home/components/ai/ai-references'; +import { AiPlanProgress, AiPlanStep } from '@home/components/ai/ai-action.models'; + +export interface AiPlanRun { + auto: boolean; + skipped: number[]; +} + +type AiPlanMark = 'todo' | 'now' | 'done' | 'off'; + +@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); + + @Output() run = new EventEmitter(); + @Output() change = new EventEmitter(); + + private cleared = signal>(new Set()); + + private host = inject(ElementRef); + + private chips = effect(() => { + const steps = this.steps(); + 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: ''}))); + } + }); + }); + }); + + marks = computed(() => { + const progress = this.progress(); + return this.steps().map((_, index) => { + const number = index + 1; + if (progress?.done.includes(number)) { + return 'done'; + } + if (progress?.skipped.includes(number)) { + return 'off'; + } + return progress?.now === number ? 'now' : 'todo'; + }); + }); + + counted = computed(() => this.gate() + ? this.steps().filter((step, index) => !step.optional || !this.cleared().has(index)).length + : this.marks().filter(mark => mark !== 'off').length); + + done = computed(() => this.marks().filter(mark => mark === 'done').length); + + 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..628dd9989f 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..bde8d07d8e 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-text-lh, 22px); + } + + .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 { + position: absolute; + top: 50%; + right: 19px; + 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: none; + color: var(--k-faint); + font: 400 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + 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..1cd192c1fe 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,36 @@ // 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 { 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 +40,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 +59,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 +67,72 @@ 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; + + @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,7 +165,11 @@ 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 { @@ -123,6 +179,14 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } 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 +194,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 +240,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 { @@ -192,11 +266,18 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr this.message.setValue(value); this.hasText.set(!!value); setTimeout(() => { - this.textarea?.nativeElement.focus(); + const field = this.textarea?.nativeElement; + field?.focus(); + field?.setSelectionRange(field.value.length, field.value.length); this.resize(); }); } + toggleAutoApprove(event: Event): void { + this.autoApprove = (event.target as HTMLInputElement).checked; + this.autoApproveChange.emit(this.autoApprove); + } + openFilePicker(): void { this.fileInput?.nativeElement.click(); } @@ -228,7 +309,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,7 +420,7 @@ 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'; } 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..05858aa02a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html @@ -0,0 +1,181 @@ + +@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) { + + } + {{ step.question }} + @if (step.why) { + {{ step.why }} + } +
+
+ @if (isFree(step) && isColor(step)) { +
+ +
+ } @else if (isFree(step)) { +
+
+ + {{ 'ai-assistant.question.your-answer' | translate }} + @if (step.secret) { + + } @else { + + } + +
+
+ } @else if (step.multiple) { +
+ @for (option of step.options; track option.label) { + + } + +
+ } @else if (isChipRow(step)) { +
+ @for (option of step.options; track option.label) { + + } + @if (isColor(step)) { + + } @else { + + } +
+ @if (isOther(step) && !isColor(step)) { + + } @else if (chosenHint(step); as hint) { +

{{ hint }}

+ } + } @else { +
+ @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..aff1efef08 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiQuestion, AiQuestionAnswer } from '@shared/models/solution-creator.models'; +import { TbPopoverService } from '@shared/components/popover.service'; +import { ColorPickerPanelComponent } from '@shared/components/color-picker/color-picker-panel.component'; +import tinycolor from 'tinycolor2'; + +const MULTI_SEPARATOR = ', '; + +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 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 question = questions.find(item => line.startsWith(item.question.trim() + ' ')); + if (!question) { + return null; + } + answers.push({question, answer: line.slice(question.question.trim().length).trim()}); + } + return answers.length ? answers : null; +} + +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', + standalone: false +}) +export class AiQuestionComponent { + + questions = input.required(); + answered = input(null); + disabled = input(false); + 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; + + at = signal(0); + move = signal<'next' | 'back' | null>(null); + private picked = signal>({}); + 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) ? '' : this.defaultOf(question); + } + + isFree(question: AiQuestion): boolean { + return !question.options?.length; + } + + 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 { + return this.typed()[question.id] ?? ''; + } + + ready(question: AiQuestion): boolean { + if (question.multiple && !this.isFree(question)) { + return true; + } + return this.isOther(question) ? !!this.otherText(question).trim() : !!this.valueOf(question); + } + + sheet = computed(() => this.questions().length > 1 && this.questions().every(question => + !question.multiple && !this.isFree(question) && (this.isChipRow(question) || question.options.length <= 3))); + + allReady = computed(() => this.questions().every(question => this.ready(question))); + + finish(): void { + if (!this.disabled() && this.questions().every(question => this.ready(question))) { + this.done.emit(this.answers()); + } + } + + isChipRow(question: AiQuestion): boolean { + return !question.multiple && question.options.length >= 2 && question.options.length <= (this.isColor(question) ? 6 : 4) + && question.options.every(option => option.label.length <= 24); + } + + 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})); + } + + isColor(question: AiQuestion): boolean { + return !question.multiple && !question.secret + && (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label)))); + } + + pickColor(question: AiQuestion, trigger: HTMLElement): void { + if (this.disabled()) { + return; + } + if (this.popoverService.hasPopover(trigger)) { + this.popoverService.hidePopover(trigger); + return; + } + const current = aiColorOf(this.isOther(question) ? this.otherText(question) : this.valueOf(question)) ?? '#305680'; + const popover = this.popoverService.displayPopover({ + trigger, + renderer: this.renderer, + hostView: this.viewContainerRef, + componentType: ColorPickerPanelComponent, + preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'], + context: {color: current, disableAlpha: true, colorCancelButton: true}, + showCloseButton: false, + popoverContentStyle: {padding: '12px 4px 12px 12px'}, + isModal: true + }); + popover.tbComponentRef.instance.popover = popover; + popover.tbComponentRef.instance.colorSelected.subscribe((color: string) => { + popover.hide(); + const hex = tinycolor(color).toHexString(); + if (!question.options?.length) { + this.typed.update(values => ({...values, [question.id]: hex})); + return; + } + const option = question.options.find(item => aiColorOf(item.label)?.toLowerCase() === hex); + if (option) { + this.pick(question, option.label); + } else { + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: hex})); + } + }); + popover.tbComponentRef.instance.colorCancelDialog.subscribe(() => popover.hide()); + } + + 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) || this.disabled()) { + 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 { + if (!this.disabled()) { + 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'); + } + 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-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts new file mode 100644 index 0000000000..6ccf98dd90 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -0,0 +1,236 @@ +// 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 (facts().length) { +
+ @for (fact of facts(); 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)); + + 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; + }); + + hasFoot = computed(() => !!this.note() || this.facts().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..2da3acfb33 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -0,0 +1,331 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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 { 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, + 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 this.translate.currentLang?.replace('_', '-') || undefined; + } + + private time(ts: number): string { + const date = new Date(ts); + const today = new Date().toDateString() === date.toDateString(); + return new Intl.DateTimeFormat(this.locale(), today ? {hour: '2-digit', minute: '2-digit'} + : {day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit'}).format(date); + } +} 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..71899ef487 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts @@ -0,0 +1,69 @@ +// 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); + + name = input.required(); + + meta = input(); + + badge = input(); + + url = input(); + + state = input(); + + alarm = input(); + + hub = input(); + + kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule())); +} 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..b714aef730 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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; + 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: 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..6df80b9e27 --- /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) : 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..48acad0a84 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts @@ -0,0 +1,304 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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)); +} + +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]); + fragment.append(reference ? chip(reference) : match[1]); + rest = rest.slice(match.index + match[1].length); + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); +} + +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; + const icon = document.createElement('span'); + icon.className = 'mat-icon notranslate material-icons mat-ligature-font k-ent-ic'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = kind.icon; + code.append(icon, 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'; + +export function decorateSeverities(root: HTMLElement, severities: string[] | undefined, label: (severity: string) => string): void { + if (!severities?.length) { + return; + } + const pattern = new RegExp(`(? severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu'); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: node => node.parentElement?.closest(SEVERITY_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 => { + 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 severity = match[1].toUpperCase(); + const chip = document.createElement('span'); + chip.className = 'k-sev ' + severity.toLowerCase(); + chip.append(aiSevMarkElement(severity), label(severity)); + fragment.append(chip); + rest = rest.slice(match.index + match[1].length); + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); + }); +} + +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..d3f544b305 --- /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-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..c51e0c5498 --- /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-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-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..ddee5bfc4e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts @@ -0,0 +1,373 @@ +// 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 div = document.createElement('div'); + div.innerHTML = html; + return (div.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..d44f437a08 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -0,0 +1,73 @@ +// 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-54) 0%, var(--tb-ink) 42%, var(--tb-ink-54) 58%, var(--tb-ink-54) 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 { + margin-left: auto; + padding-left: 12px; + 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-76); + } +} 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.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index d837940241..a6e37d5ae5 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,84 @@ 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 { 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, + 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..db1327463d --- /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..ab5e08a289 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html @@ -0,0 +1,138 @@ + +@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..8153a44b15 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts @@ -0,0 +1,329 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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 OPERATIONS: Record = {C: 'create', R: 'read', U: 'update', D: 'delete'}; + +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 ?? ''; + return {ops: permissions.toUpperCase().split('').filter(letter => OPERATIONS[letter]) + .map(letter => this.translate.instant('solution-creator.pane.op-' + OPERATIONS[letter]))}; + } + 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(); + } + + dashboardUser(row: AggregatedEntityResult): string { + return this.userName(row.primary?.additionalData?.userId); + } + + 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 userName(userId: string | undefined): string { + return userId ? this.findUser(userId)?.additionalData?.name ?? '' : ''; + } + + 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..ef78179801 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html @@ -0,0 +1,284 @@ + +
+
+ @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 }}
+ + {{ profile.name }} + + {{ 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 }} + +
+ @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..6eab2be7e8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts @@ -0,0 +1,227 @@ +// 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'}; + +@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 (iam.permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]); + } + + 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..5895225f5a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -0,0 +1,423 @@ + +
+ + +
+ @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) { + + } + + +
+ @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..f501c1bbf6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -0,0 +1,818 @@ +// 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-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(4, minmax(0, 1fr)); + gap: 14px 24px; + align-items: start; + + @media (max-width: 860px) { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + @media (max-width: 480px) { + grid-template-columns: minmax(0, 1fr); + } +} + +.sol-feat { + display: flex; + gap: 10px; + min-width: 0; + + > .mat-icon { + flex: none; + font-size: 20px; + width: 20px; + height: 20px; + line-height: 16px; + margin-top: 1px; + color: var(--k-grey); + } + + > div { + display: grid; + gap: 2px; + 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..4291e66394 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -0,0 +1,1863 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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 } from '@shared/models/ai-chat.models'; +import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; +import { + catchError, + 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); +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-chat', + templateUrl: './solution-chat.component.html', + styleUrls: ['./solution-chat.component.scss'], + standalone: false +}) +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 '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)); + }); + + 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() + ? '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); + return this.solutionCreator.getSolutionById(data.solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( + 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'); + if (last >= 0 && (messages[last] as GeneralChatMessage).content === msg) { + this.messages.set([...messages.slice(0, last), ...messages.slice(last + 1)]); + this.messageSteps = this.messageSteps.slice(0, -1); + } + setTimeout(() => this.promptInput?.setValue(msg)); + } + + 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): boolean { + if (!this.stopping() || err?.status !== 409) { + return false; + } + this.stopping.set(false); + this.stoppedAction = again; + this.messageSteps = [...this.messageSteps, this.solutionStep()]; + this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('solution-creator.stopped'), status: 'STOPPED', time: Date.now()}]); + 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); + } + } + + nextStep() { + if(this.solutionInfo.states[this.solutionStep()]?.status === SolutionStepStatus.READY) { + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + 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.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + 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()) && !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()) && !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.back(); + } + }); + } + }) + } + + 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; + }); + } + + updatedDashboardOverview(dashboards: DashboardsOverview[]) { + this.solutionCreator.updateSolutionData(this.solutionId, 'dashboardsOverview', dashboards, {ignoreLoading: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe(value => { + this.solutionInfo = value; + }); + } + + 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 (!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 visible = (msg: ChatMessage) => msg.from === 'AI' || (msg.from === 'USER' && !/^<[a-z-]+\/>$/.test(((msg as GeneralChatMessage).content ?? '').trim())); + const tagged = steps.flatMap(step => (this.solutionInfo.states[step]?.messages ?? []).filter(visible).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 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 && !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 100% 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 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-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts index 2f846be65b..c59c4120fa 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, @@ -222,7 +219,12 @@ export class AlarmTableConfig extends EntityTableConfig displayDetails: true, allowAssign: 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/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/dashboard-page.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html index 93e4466c72..1d5e60c7cb 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html @@ -66,6 +66,7 @@ } @else { @if (!isPublicUser()) { + }
@if (!isEdit && !isPublicUser()) { + } } - @if (showConfigureWithAi) { - - - } @if (isEdit) { } - @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..7d0728997a 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,17 @@ 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(() => { + this.updateData(false); + }); } this.pageMode = this.entitiesTableConfig.pageMode; @@ -567,6 +559,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..a18d4f90c2 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)) { @@ -123,6 +126,9 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl } ngOnDestroy() { + if (this.entitiesTableConfig?.aiAssistantConfig?.view?.entityView) { + this.panelService.teardown(); + } super.ngOnDestroy(); } @@ -173,6 +179,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/group/entity-groups-table-config.resolver.ts b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts index 132cfff504..15f6912b61 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) { 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/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/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/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/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/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/map/map-layer-settings-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html index c37facc148..0ebf2f4deb 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html @@ -137,18 +137,19 @@ @if (apiKeyMissingWarning(); as warning) { - - warning - + + + warning + + }
diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index 852d1c4742..1d76d5d396 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) { +
+ + + + + +
+ +
+
+ } @else { +
+ + @if (waitItem(); as wait) { + + } + + + + + +
+ } + + +@if (solutionId()) { + +} @else if (cli()) { + + @if (!railOpen()) { + + } + +} @else { + + @if (!railOpen()) { + + } + +} + + + + + + @if (solution.built) { + + } + @if (solution.installed) { + + } + + + + + + + + + + + + diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss new file mode 100644 index 0000000000..943542683a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -0,0 +1,706 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '../../components/ai/ai-icon-button' as *; +@import "constants"; + +:host { + position: relative; + display: flex; + width: 100%; + height: 100%; + min-height: 0; + overflow: hidden; + background: #f4f6f7; + 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); +} + +.ai-rail .ai-ib, .ai-bar-chats { + @include ai-icon-button($color: var(--tb-ink-60)); +} + +.ai-panel-icon { + width: 20px; + height: 20px; + fill: currentColor; +} + +.ai-rail { + position: relative; + flex: none; + display: flex; + flex-direction: column; + width: 48px; + min-height: 0; + overflow: hidden; + transition: width $sidenav-anim-timing; +} + +.ai-rail-in { + animation: ai-rail-fade-in $sidenav-anim-timing both; +} + +.ai-rail-out { + position: absolute; + top: 0; + bottom: 0; + left: 0; + pointer-events: none; + animation: ai-rail-fade-out 200ms ease-out both; +} + +.ai-strip.ai-rail-out { + width: 48px; +} + +.ai-rail-panel.ai-rail-out { + width: 256px; +} + +@keyframes ai-rail-fade-in { + from { + opacity: 0; + } +} + +@keyframes ai-rail-fade-out { + to { + opacity: 0; + } +} + +@keyframes ai-rail-hold { + to { + opacity: 1; + } +} + +:host(.rail-open) .ai-rail { + width: 256px; +} + +.ai-strip { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 14px 0 10px; +} + +.ai-rail-panel { + min-width: 256px; + height: 100%; + display: flex; + flex-direction: column; + box-sizing: border-box; + padding: 8px 6px 10px 10px; +} + +.ai-rail-head { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 44px; + box-sizing: border-box; + margin-right: 4px; + padding-left: 8px; + + h2 { + margin: 0; + font: 500 var(--chat-head)/22px var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); + } +} + +.ai-nav { + display: grid; + grid-template-columns: 20px minmax(0, 1fr); + align-items: center; + gap: 10px; + width: calc(100% - 4px); + margin-right: 4px; + padding: 6px 10px 6px 8px; + border: 0; + border-radius: 8px; + background: none; + font: 500 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + text-align: left; + cursor: pointer; + transition: background-color .12s ease; + + .mat-icon { + font-size: 19px; + width: 20px; + height: 19px; + text-align: center; + color: var(--tb-ink-60); + } + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &.active { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + + .mat-icon { + color: var(--tb-ink); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.ai-find { + display: flex; + align-items: center; + gap: 10px; + height: 32px; + margin: 2px 4px 0 0; + padding: 0 10px 0 8px; + border-radius: 8px; + cursor: text; + transition: background-color .12s ease, box-shadow .12s ease; + + .mat-icon { + flex: none; + font-size: 19px; + width: 20px; + height: 19px; + text-align: center; + color: var(--tb-ink-60); + } + + input { + flex: 1; + min-width: 0; + padding: 0; + border: 0; + outline: 0; + background: none; + font: 400 13.5px/18px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + + &::placeholder { + color: var(--tb-ink-60); + } + + &::-webkit-search-cancel-button { + display: none; + } + } + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &.on { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + } + + &:focus-within { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke-hover); + + .mat-icon { + color: var(--tb-ink); + } + + .ai-find-key { + visibility: hidden; + } + } +} + +.ai-find-key { + flex: none; + 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: none; + font: 400 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + color: var(--k-faint); + + @media (max-width: 599px), (pointer: coarse) { + display: none; + } +} + +.ai-find-clear { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + margin-right: -4px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } +} + +.ai-list { + flex: 1; + min-height: 0; + overflow-y: auto; + margin-top: 4px; + padding-right: 4px; +} + +.ai-sect { + margin-top: 18px; + + &:first-child { + margin-top: 12px; + } + + h3 { + margin: 0 8px 4px; + font: 500 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: 0.1px; + color: var(--tb-ink-54); + } +} + +.ai-row { + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + column-gap: 8px; + min-height: 34px; + box-sizing: border-box; + padding: 7px 8px; + border-radius: 8px; + cursor: pointer; + transition: background-color .12s ease; + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.active { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + + .ai-row-title { + font-weight: 500; + } + } + + &.editing { + grid-template-columns: minmax(0, 1fr); + padding: 2px; + cursor: default; + } + + &:hover, &:focus-within { + .tb-ai-status-mark { + visibility: hidden; + } + + .ai-row-menu { + opacity: 1; + } + } + + .tb-ai-status-mark { + margin-right: 2px; + } +} + +.ai-row.attn .ai-row-title { + font-weight: 500; +} + +.ai-row-title { + display: block; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 400 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + +.ai-row-ic { + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + vertical-align: -2px; + margin-right: 5px; + color: var(--tb-ink-54); +} + +.ai-row.active .ai-row-ic { + color: var(--ai-action); +} + +.ai-row-menu { + position: absolute; + top: 50%; + right: 4px; + transform: translateY(-50%); + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + padding: 0; + border: 0; + border-radius: 8px; + background: var(--tb-surface); + color: var(--tb-ink-60); + cursor: pointer; + opacity: 0; + transition: opacity .12s ease; + + &:hover { + color: var(--tb-ink); + } + + &:focus-visible, &[aria-expanded="true"] { + opacity: 1; + } + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.ai-rename { + width: 100%; + height: 30px; + box-sizing: border-box; + padding: 0 8px; + border: 0; + border-radius: 8px; + outline: 0; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1.5px var(--ai-teal-500); + font: 400 13.5px/19px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + +.ai-empty { + margin: 16px 10px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); +} + +.ai-canvas { + flex: 1; + margin: 8px 8px 8px 0; + border-radius: 12px; + box-shadow: var(--tb-soft-shadow); + overflow: hidden; +} + +.ai-canvas.ai-solution { + width: auto; + height: auto; + min-width: 0; + background: var(--tb-surface, #fff); +} + +.ai-canvas .ai-bar-chats { + display: none; + margin-left: -8px; +} + +@media (max-width: 899px) { + :host(.rail-open) .ai-rail { + position: absolute; + z-index: 40; + top: 0; + bottom: 0; + left: 0; + background: #f4f6f7; + box-shadow: 8px 0 24px rgba(0, 0, 0, 0.12); + } + + :host(.rail-open) .ai-canvas { + margin-left: 48px; + + &::after { + content: ''; + position: absolute; + inset: 0; + z-index: 30; + border-radius: inherit; + background: rgba(16, 24, 40, 0.24); + cursor: pointer; + animation: ai-rail-fade-in $sidenav-anim-timing both; + } + } +} + +@media (max-width: 599px) { + .ai-rail, :host(.rail-open) .ai-rail { + position: absolute; + z-index: 40; + top: 0; + bottom: 0; + left: 0; + width: min(300px, 86vw); + background: #f4f6f7; + box-shadow: 8px 0 24px rgba(0, 0, 0, 0.12); + } + + .ai-rail { + visibility: hidden; + transform: translateX(-100%); + transition: transform $sidenav-anim-timing, visibility 0s linear 400ms; + } + + :host(.rail-open) .ai-rail { + visibility: visible; + transform: none; + transition: transform $sidenav-anim-timing; + } + + .ai-strip { + display: none; + } + + .ai-rail-in { + animation: none; + } + + .ai-rail-panel.ai-rail-out { + animation: ai-rail-hold $sidenav-anim-timing both; + } + + .ai-canvas, :host(.rail-open) .ai-canvas { + margin: 0; + border-radius: 0; + box-shadow: none; + } + + .ai-canvas .ai-bar-chats { + display: inline-flex; + } +} + +.ai-wait-btn .ai-wait-n { + min-width: 20px; + height: 20px; + padding: 0 6px; + box-sizing: border-box; + border-radius: 10px; + background: var(--tb-ink); + color: #fff; + font: 500 11.5px/20px var(--tb-font); + font-style: normal; + font-variant-numeric: tabular-nums; + text-align: center; +} + +.ai-wait-btn:hover .ai-wait-n { + background: #000; +} + +.ai-bar-chats .ai-badge { + position: absolute; + top: 2px; + left: 18px; + min-width: 16px; + height: 16px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 8px; + background: var(--tb-ink); + color: #fff; + font: 500 11px/16px Roboto, sans-serif; + font-style: normal; + font-variant-numeric: tabular-nums; + text-align: center; + box-shadow: 0 0 0 2px var(--tb-surface); + pointer-events: none; +} + +.ai-row-title mark, .ai-row-s mark { + padding: 0 1px; + border-radius: 2px; + background: color-mix(in oklab, var(--ai-teal-500) 18%, transparent); + color: inherit; +} + +.ai-row-s { + display: block; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 400 12px/16px var(--tb-font); + color: var(--tb-ink-54); +} + +.ai-panel-foot { + flex: none; + display: grid; + gap: 2px; + margin: 6px 4px 0 0; + padding-top: 6px; + border-top: 1px solid var(--k-stroke); + + .ai-nav.ai-nav-cli { + width: 100%; + margin-right: 0; + } +} + +.ai-nav.ai-nav-cli { + grid-template-columns: 28px minmax(0, 1fr); + gap: 10px; + padding: 6px 8px 6px 6px; + + &.active { + background: none; + box-shadow: none; + } +} + +.ai-cli-ic { + width: 28px; + height: 28px; + border-radius: 8px; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--ai-dark); + color: var(--ai-on-dark); + transition: background-color .15s cubic-bezier(.2, 0, 0, 1), color .15s cubic-bezier(.2, 0, 0, 1), opacity .15s cubic-bezier(.2, 0, 0, 1); +} + +.ai-nav .ai-cli-ic .mat-icon { + font-size: 17px; + width: 17px; + height: 17px; + color: inherit; +} + +.ai-cli-lbl { + display: flex; + flex-direction: column; + min-width: 0; + + small { + font: 500 10.5px/14px var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + color: var(--tb-ink-54); + } + + > span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font: 500 13.5px/18px var(--tb-font); + color: var(--tb-ink); + } +} + +.ai-strip { + flex: 1; + min-height: 0; +} + +.ai-strip .ai-strip-cli { + margin-top: auto; + + &:hover { + background: none; + } + + .ai-cli-ic { + width: 26px; + height: 26px; + border-radius: 8px; + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + color: inherit; + } + } +} + +.ai-nav.ai-nav-cli:hover .ai-cli-ic, .ai-strip-cli:hover .ai-cli-ic { + background: #2c3c46; + color: #fff; +} + +.ai-nav.ai-nav-cli.active .ai-cli-ic, .ai-strip-cli.active .ai-cli-ic { + background: var(--ai-dark); + color: var(--ai-on-dark); + opacity: .38; +} + +.ai-nav.ai-nav-cli.active:hover .ai-cli-ic, .ai-strip-cli.active:hover .ai-cli-ic { + opacity: .6; +} + +.ai-nav.ai-nav-cli.active .ai-cli-lbl > span { + color: var(--tb-ink-54); +} + +.ai-nav.ai-nav-cli.active:hover .ai-cli-lbl > span { + color: var(--tb-ink-76); +} + +@media (prefers-reduced-motion: reduce) { + .ai-rail, :host(.rail-open) .ai-rail { + transition: none; + } + + .ai-rail-in, .ai-rail-out, :host(.rail-open) .ai-canvas::after { + animation-duration: 1ms; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts new file mode 100644 index 0000000000..3db450a872 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -0,0 +1,634 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TourService } from '@core/services/tour.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + HostListener, + inject, + OnDestroy, + OnInit, + signal, + untracked, + ViewChild +} from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { forkJoin, of } from 'rxjs'; +import { catchError } from 'rxjs/operators'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; +import { DAY, WEEK } from '@shared/models/time/time.models'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { NEW_SOLUTION_ID, SolutionInfo } from '@shared/models/solution-creator.models'; +import { SolutionChatComponent } from '@home/components/ai/solution/solution-chat.component'; + +export interface AiRailRow { + id: string; + title: string; + createdTime: number; + pinned: boolean; + pinnedTime?: number; + prompt?: string; + chat?: ChatInfo; + solution?: SolutionInfo; +} + +export interface AiChatsGroup { + label: string; + chats: AiRailRow[]; +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-ai-assistant', + templateUrl: './ai-assistant.component.html', + styleUrls: ['./ai-assistant.component.scss'], + standalone: false, + host: { + 'data-ai': '', + '[class.rail-open]': 'railOpen()' + } +}) +export class AiAssistantComponent implements OnInit, OnDestroy { + + private static readonly RAIL_OPEN_KEY = 'tbAiAssistantRailOpen'; + private static readonly NARROW_WIDTH = 900; + private static readonly REFRESH_MS = 20000; + + @ViewChild(AiChatComponent) chat: AiChatComponent; + @ViewChild(SolutionChatComponent) solutionChat: SolutionChatComponent; + @ViewChild('searchInput') searchInput: ElementRef; + + readonly toastTarget = 'aiAssistantPage'; + + readonly newSolutionId = NEW_SOLUTION_ID; + + readonly shortcutModifier = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl '; + + railOpen = signal(this.initialRailOpen()); + + query = signal(''); + + renamingId = signal(null); + + chatId = signal(undefined); + + solutionId = signal(undefined); + + getStarted = signal(false); + + cli = signal(false); + + aiChats = inject(AiChatsService); + + private aiChat = inject(AiChatService); + + aiSolutions = inject(AiSolutionsService); + + rows = computed(() => [ + ...this.aiChats.chats().map(chat => ({ + id: chat.id, title: chat.title, createdTime: chat.createdTime, pinned: !!chat.pinned, pinnedTime: chat.pinnedTime, prompt: chat.prompt, chat + })), + ...this.aiSolutions.solutions().map(solution => ({ + id: solution.id, title: this.aiSolutions.titleOf(solution), createdTime: solution.createdTime ?? 0, pinned: !!solution.pinned, solution + })) + ].sort((a, b) => b.createdTime - a.createdTime)); + + groups = computed(() => { + const query = this.query().trim().toLowerCase(); + const chats = this.rows(); + if (query) { + const found = chats.filter(chat => (chat.title ?? '').toLowerCase().includes(query) || (chat.prompt ?? '').toLowerCase().includes(query)); + return found.length + ? [{label: this.translate.instant('ai-assistant.chats-found', {count: found.length}), chats: found}] + : []; + } + const now = new Date(); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + const groups: AiChatsGroup[] = [ + {label: this.translate.instant('ai-assistant.pinned'), chats: []}, + {label: this.translate.instant('ai-assistant.today'), chats: []}, + {label: this.translate.instant('ai-assistant.yesterday'), chats: []}, + {label: this.translate.instant('ai-assistant.last-7-days'), chats: []}, + {label: this.translate.instant('ai-assistant.older'), chats: []} + ]; + for (const chat of chats) { + const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4; + groups[index].chats.push(chat); + } + const needsFirst = (row: AiRailRow) => this.needsAttention(row) ? 0 : 1; + groups.forEach(group => group.chats.sort((a, b) => needsFirst(a) - needsFirst(b))); + groups[0].chats.sort((a, b) => (b.pinnedTime ?? b.createdTime) - (a.pinnedTime ?? a.createdTime)); + return groups.filter(group => group.chats.length); + }); + + waiting = computed(() => { + const rank = (row: AiRailRow) => this.levelOf(row) === 'needs' ? 0 : 1; + return this.rows() + .filter(row => this.needsAttention(row)) + .sort((a, b) => rank(a) - rank(b) || b.createdTime - a.createdTime); + }); + + waitItem = computed<{count: number; tip: string; label: string} | null>(() => { + const waiting = this.waiting(); + if (!waiting.length || (waiting.length === 1 && this.isActive(waiting[0]))) { + return null; + } + if (waiting.length === 1) { + const title = waiting[0].title || this.translate.instant('ai-assistant.new-chat'); + return { + count: 1, + tip: this.translate.instant('ai-assistant.waiting-one-tip', {title, status: this.tipOf(waiting[0])}), + label: this.translate.instant('ai-assistant.waiting-one', {title}) + }; + } + const text = this.translate.instant('ai-assistant.waiting-many', {count: waiting.length}); + return {count: waiting.length, tip: text, label: text}; + }); + + private translate = inject(TranslateService); + private store = inject(Store); + private sanitizer = inject(DomSanitizer); + private router = inject(Router); + private route = inject(ActivatedRoute); + + private panelService = inject(AiAssistantPanelService); + + private tourService = inject(TourService); + + private initialSelection = (() => { + const params = this.route.snapshot.queryParamMap; + const solutionId = params.get('solutionId'); + if (solutionId) { + this.solutionId.set(solutionId); + } else if (params.get('chatId')) { + this.chatId.set(params.get('chatId')); + } else if (params.get('cli') === 'true') { + this.cli.set(true); + } else if (params.get('getStarted') === 'true') { + this.getStarted.set(true); + } + return true; + })(); + private host = inject>(ElementRef); + + private browsing = false; + + private pendingEdit: string | null = null; + + private ready = signal(false); + + private urlEffect = effect(() => { + const chatId = this.chatId() ?? null; + const solutionId = this.solutionId() ?? null; + const cli = this.cli() && !chatId && !solutionId ? 'true' : null; + const getStarted = this.getStarted() && !cli && !chatId && !solutionId ? 'true' : null; + const params = this.route.snapshot.queryParamMap; + if ((params.get('chatId') !== chatId || params.get('solutionId') !== solutionId || params.get('getStarted') !== getStarted + || params.get('cli') !== cli) && this.ready()) { + const browsing = this.browsing; + this.browsing = false; + this.router.navigate([], { + relativeTo: this.route, + queryParams: {chatId, solutionId, getStarted, cli}, + queryParamsHandling: 'merge', + replaceUrl: !browsing + }); + } + }); + + private leaveGetStarted = effect(() => { + if (this.chatId() || this.solutionId()) { + untracked(() => { + this.getStarted.set(false); + this.cli.set(false); + }); + } + }); + + private urlSubscription = this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(params => { + if (this.ready()) { + this.openFromUrl(params.get('chatId'), params.get('solutionId'), undefined, params.get('getStarted') === 'true', params.get('cli') === 'true'); + } + }); + + private refreshTimer = setInterval(() => { + if (!document.hidden) { + this.aiChats.refresh().subscribe({error: () => {}}); + } + }, AiAssistantComponent.REFRESH_MS); + + ngOnDestroy(): void { + clearInterval(this.refreshTimer); + } + + ngOnInit(): void { + forkJoin([ + this.aiSolutions.load().pipe(catchError(err => { + this.showErrorMessage(err); + return of([]); + })), + this.aiChats.load() + ]).subscribe({ + next: ([, chats]) => { + const params = this.route.snapshot.queryParamMap; + const handOff = this.panelService.takeHandOff(); + const first = !handOff && !params.get('chatId') && !params.get('solutionId') && !chats.length; + this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats, first || params.get('getStarted') === 'true', + params.get('cli') === 'true'); + this.ready.set(true); + if (params.get('focus') === 'composer') { + this.landOnComposer(); + } + if (params.get('chats') === 'closed') { + this.landFolded(); + } + if (handOff) { + this.newChat(); + setTimeout(() => this.chat?.sendMsgFromUser(handOff)); + } + }, + error: err => { + this.ready.set(true); + this.showErrorMessage(err); + } + }); + } + + @HostListener('document:keydown', ['$event']) + onDocumentKeydown(event: KeyboardEvent): void { + if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key.toLowerCase() === 'k') { + event.preventDefault(); + this.openSearch(); + } + } + + toggleRail(): void { + this.setRailOpen(!this.railOpen()); + } + + openSearch(): void { + this.setRailOpen(true); + setTimeout(() => this.searchInput?.nativeElement.focus()); + } + + onSearchKeydown(event: KeyboardEvent): void { + if (event.key === 'Escape') { + event.preventDefault(); + if (this.query()) { + this.query.set(''); + } else { + (event.target as HTMLInputElement).blur(); + } + } + } + + onChatClick(event: MouseEvent): void { + if (event.target === event.currentTarget) { + this.settleRail(); + } + } + + private carryOnLink = (() => { + const host = this.host.nativeElement; + const listener = (event: MouseEvent) => { + const chatId = this.chatId(); + const link = (event.target as HTMLElement | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + if (!chatId || this.solutionId() || !link || !link.closest('.ai-canvas') || link.target === '_blank' || link.getAttribute('href')?.startsWith('#') + || link.origin !== window.location.origin || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey + || link.pathname === '/ai-assistant' || link.pathname.startsWith('/ai-assistant/')) { + return; + } + this.panelService.carryChatToPage(chatId); + }; + host.addEventListener('click', listener, true); + inject(DestroyRef).onDestroy(() => host.removeEventListener('click', listener, true)); + return true; + })(); + + marked(text: string | undefined): {text: string; hit: boolean}[] { + const value = text ?? ''; + const query = this.query().trim(); + const at = query ? value.toLowerCase().indexOf(query.toLowerCase()) : -1; + return at < 0 ? [{text: value, hit: false}] : [ + {text: value.slice(0, at), hit: false}, + {text: value.slice(at, at + query.length), hit: true}, + {text: value.slice(at + query.length), hit: false} + ].filter(part => part.text); + } + + snippetOf(row: AiRailRow): {text: string; hit: boolean}[] | null { + const query = this.query().trim().toLowerCase(); + const prompt = row.prompt ?? ''; + const at = query ? prompt.toLowerCase().indexOf(query) : -1; + if (!query || (row.title ?? '').toLowerCase().includes(query) || at < 0) { + return null; + } + let start = Math.max(0, at - 18); + const space = prompt.indexOf(' ', start); + if (start && space > -1 && space < at) { + start = space + 1; + } + return [ + {text: (start ? '…' : '') + prompt.slice(start, at), hit: false}, + {text: prompt.slice(at, at + query.length), hit: true}, + {text: prompt.slice(at + query.length, at + query.length + 40), hit: false} + ].filter(part => part.text); + } + + runAgain(chat: ChatInfo): void { + const start = (prompt: string | undefined) => { + if (!prompt?.trim()) { + return; + } + this.newChat(); + setTimeout(() => this.chat?.ask(prompt.trim())); + }; + if (chat.prompt) { + start(chat.prompt); + return; + } + this.aiChat.getChatMessages(chat.id, {ignoreLoading: true}).subscribe({ + next: messages => start((messages.find(message => message.from === 'USER') as {content?: string} | undefined)?.content), + error: err => this.showErrorMessage(err) + }); + } + + newChat(): void { + this.settleRail(); + this.browsing = !!this.chatId() || !!this.solutionId() || this.getStarted() || this.cli(); + this.solutionId.set(undefined); + this.chatId.set(undefined); + this.getStarted.set(false); + this.cli.set(false); + setTimeout(() => this.chat?.focus()); + } + + openGetStarted(): void { + this.settleRail(); + this.browsing = !!this.chatId() || !!this.solutionId() || !this.getStarted() || this.cli(); + this.solutionId.set(undefined); + this.chatId.set(undefined); + this.cli.set(false); + this.getStarted.set(true); + } + + openCli(): void { + if (this.cli()) { + this.openGetStarted(); + return; + } + this.settleRail(); + this.browsing = true; + this.solutionId.set(undefined); + this.chatId.set(undefined); + this.getStarted.set(false); + this.cli.set(true); + } + + takeTour(): void { + this.tourService.playAssistantTour(); + } + + newSolution(): void { + this.settleRail(); + this.openSolution(NEW_SOLUTION_ID); + } + + selectRow(row: AiRailRow): void { + if (row.solution) { + this.settleRail(); + this.openSolution(row.solution.id); + } else if (row.chat) { + this.selectChat(row.chat); + } + } + + isActive(row: AiRailRow): boolean { + return row.solution ? row.id === this.solutionId() : row.id === this.chatId() && !this.solutionId(); + } + + editDesign(solution: SolutionInfo): void { + if (this.solutionId() === solution.id && this.solutionChat) { + this.solutionChat.editDesign(); + return; + } + this.pendingEdit = solution.id; + this.openSolution(solution.id); + } + + onSolutionLoaded(solutionId: string): void { + if (this.pendingEdit === solutionId) { + this.pendingEdit = null; + this.solutionChat?.editDesign(); + } + } + + uninstallSolution(solution: SolutionInfo): void { + this.aiSolutions.confirmAndUninstall(solution).subscribe({ + next: info => { + if (info && this.solutionId() === solution.id) { + this.solutionChat?.updatedSolution(info); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + deleteSolution(solution: SolutionInfo): void { + this.aiSolutions.confirmAndDelete(solution).subscribe({ + next: deleted => { + if (deleted && this.solutionId() === solution.id) { + this.solutionId.set(undefined); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + private openSolution(solutionId: string): void { + this.browsing = solutionId !== this.solutionId() || this.cli(); + this.cli.set(false); + this.chatId.set(undefined); + this.solutionId.set(solutionId); + } + + levelOf(row: AiRailRow): ChatLevel | null { + return row.chat ? this.aiChats.levelOf(row.chat) : this.aiSolutions.levelOf(row.solution, this.isActive(row)); + } + + tipOf(row: AiRailRow): string { + return row.chat ? this.aiChats.tipOf(row.chat) : this.aiSolutions.tipOf(row.solution, this.isActive(row)); + } + + needsAttention(row: AiRailRow): boolean { + const level = this.levelOf(row); + return level === 'needs' || level === 'error'; + } + + togglePinnedSolution(solution: SolutionInfo): void { + this.aiSolutions.setPinned(solution, !solution.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + + openWaiting(): void { + const waiting = this.waiting(); + if (waiting.length === 1) { + this.selectRow(waiting[0]); + return; + } + this.setRailOpen(true); + setTimeout(() => this.host.nativeElement.querySelector('.ai-row.attn')?.scrollIntoView({block: 'nearest'})); + } + + selectChat(chat: ChatInfo): void { + this.settleRail(); + this.browsing = chat.id !== this.chatId() || !!this.solutionId() || this.cli(); + this.solutionId.set(undefined); + this.cli.set(false); + this.chatId.set(chat.id); + } + + startRename(chat: {id: string}): void { + this.setRailOpen(true); + this.renamingId.set(chat.id); + setTimeout(() => { + const input = this.host.nativeElement.querySelector('.ai-rename'); + input?.focus(); + input?.select(); + }); + } + + onRenameKeydown(event: KeyboardEvent): void { + if (event.isComposing) { + return; + } + if (event.key === 'Enter') { + (event.target as HTMLInputElement).blur(); + } else if (event.key === 'Escape') { + this.renamingId.set(null); + } + } + + finishRename(row: AiRailRow, value: string): void { + if (this.renamingId() !== row.id) { + return; + } + this.renamingId.set(null); + const title = value.trim(); + if (!title || title === row.title) { + return; + } + if (row.solution) { + this.aiSolutions.rename(row.solution, title).subscribe({ + next: info => { + if (this.solutionId() === row.id) { + this.solutionChat?.updatedSolution(info); + } + }, + error: err => this.showErrorMessage(err) + }); + } else { + this.aiChats.rename(row.id, title).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + togglePinned(chat: ChatInfo): void { + this.aiChats.setPinned(chat.id, !chat.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + + deleteChat(chat: ChatInfo): void { + this.aiChats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); + } + + private openFromUrl(chatId: string | null, solutionId: string | null, chats = this.aiChats.chats(), getStarted = false, cli = false): void { + const knownSolution = !solutionId || solutionId === NEW_SOLUTION_ID || !this.aiSolutions.loaded() || !!this.aiSolutions.find(solutionId); + if (!knownSolution) { + this.router.navigate([], { + relativeTo: this.route, + queryParams: {chatId: null, solutionId: NEW_SOLUTION_ID}, + queryParamsHandling: 'merge', + replaceUrl: true + }); + return; + } + const nextSolution = solutionId || undefined; + if (nextSolution !== this.solutionId()) { + this.solutionId.set(nextSolution); + } + const known = !nextSolution && !!chatId && chats.some(chat => chat.id === chatId); + const next = known ? chatId : undefined; + if (next !== this.chatId()) { + this.chatId.set(next); + } + const showCli = cli && !nextSolution && !next; + this.cli.set(showCli); + this.getStarted.set(getStarted && !showCli && !nextSolution && !next); + } + + private landFolded(): void { + this.railOpen.set(false); + this.router.navigate([], {relativeTo: this.route, queryParams: {chats: null}, queryParamsHandling: 'merge', replaceUrl: true}); + } + + private landOnComposer(): void { + this.railOpen.set(false); + this.router.navigate([], {relativeTo: this.route, queryParams: {focus: null}, queryParamsHandling: 'merge', replaceUrl: true}); + if (matchMedia('(hover: hover) and (pointer: fine)').matches) { + setTimeout(() => { + const field = this.host.nativeElement.querySelector('.tb-ai-composer textarea'); + field?.focus({preventScroll: true}); + field?.scrollIntoView({block: 'nearest'}); + }, 300); + } + } + + private setRailOpen(open: boolean): void { + this.railOpen.set(open); + try { + sessionStorage.setItem(AiAssistantComponent.RAIL_OPEN_KEY, open ? '1' : '0'); + } catch { + return; + } + } + + private settleRail(): void { + if (this.railOpen() && window.innerWidth < AiAssistantComponent.NARROW_WIDTH) { + this.setRailOpen(false); + } + } + + private initialRailOpen(): boolean { + try { + const stored = sessionStorage.getItem(AiAssistantComponent.RAIL_OPEN_KEY); + return stored === null ? window.innerWidth >= AiAssistantComponent.NARROW_WIDTH : stored === '1'; + } catch { + return true; + } + } + + private showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + this.store.dispatch(new ActionNotificationShow({ + message: parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message, + target: this.toastTarget, + modern: true, + type: 'error', + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts new file mode 100644 index 0000000000..a92dd5563d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { AiAssistantRoutingModule } from '@home/pages/ai-assistant/ai-assistant-routing.module'; + +@NgModule({ + imports: [ + AiAssistantRoutingModule + ] +}) +export class AiAssistantModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html new file mode 100644 index 0000000000..f2efef31ec --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html @@ -0,0 +1,237 @@ + +
+ + +
+ + +
+
+
+
+ +
+
+ +

{{ 'ai-assistant.cli.hero.title' | translate }}

+

{{ 'ai-assistant.cli.hero.lead' | translate }}

+
+
+
+ + + {{ 'ai-assistant.cli.hero.docs' | translate }} + + +
+
+
+
+
+ +
+
+

{{ 'ai-assistant.cli.how.title' | translate }}

+
    +
  1. +
    + @for (agent of agents; track agent.id) { + + } +
    + {{ 'ai-assistant.cli.how.agent.title' | translate }} +

    {{ 'ai-assistant.cli.how.agent.text' | translate }}

    +
  2. +
  3. + + {{ 'ai-assistant.cli.how.files.title' | translate }} +

    {{ 'ai-assistant.cli.how.files.text' | translate }}

    +
  4. +
  5. + + {{ 'ai-assistant.cli.how.deploy.title' | translate }} +

    {{ 'ai-assistant.cli.how.deploy.text' | translate }}

    +
  6. +
+
+ +
+
+

{{ 'ai-assistant.cli.steps.title' | translate }}

+

{{ 'ai-assistant.cli.steps.hint' | translate }}

+
+
    +
  1. + +
    +
    + {{ 'ai-assistant.cli.setup.title' | translate }} +
    + @for (item of ways; track item) { + + } +
    +
    +
    +
      + @if (way() === 'terminal') { +
    1. + {{ 'ai-assistant.cli.setup.run-install' | translate }} +
      +
    2. +
    3. + {{ 'ai-assistant.cli.setup.accept-folder' | translate }} +

      @for (part of 'ai-assistant.cli.setup.accept' | tbAiSlots; track $index) {@if (part.slot === 'folder') {thingsboard-project.} @else {{{ part.text }}}}

      +
    4. +
    5. + {{ 'ai-assistant.cli.setup.paste-url' | translate }} +
      +
    6. +
    7. + {{ 'ai-assistant.cli.setup.api-key' | translate }} +

      {{ 'ai-assistant.cli.setup.api-key-text' | translate }}

      + +
    8. +
    9. + {{ 'ai-assistant.cli.setup.start-agent' | translate }} +

      {{ 'ai-assistant.cli.setup.start-agent-text' | translate }}

      +

      @for (part of 'ai-assistant.cli.setup.both-agents' | tbAiSlots; track $index) {@switch (part.slot) {@case ('claude') {claude} @case ('antigravity') {antigravity.} @default {{{ part.text }}}}}

      +

      {{ 'ai-assistant.cli.setup.come-back-folder' | translate }}

      +
      +
    10. + } @else { +
    11. + {{ 'ai-assistant.cli.setup.agent-start' | translate }} +
      +
    12. +
    13. + {{ 'ai-assistant.cli.setup.agent-send' | translate }} +
      +

      {{ 'ai-assistant.cli.setup.agent-allow' | translate }}

      +
    14. +
    15. + {{ 'ai-assistant.cli.setup.agent-connect' | translate }} +

      {{ 'ai-assistant.cli.setup.agent-connect-text' | translate }}

      +
      +
    16. +
    17. + {{ 'ai-assistant.cli.setup.agent-key' | translate }} +

      {{ 'ai-assistant.cli.setup.agent-key-text' | translate }}

      + +
    18. +
    19. + {{ 'ai-assistant.cli.setup.agent-restart' | translate }} +

      @for (part of 'ai-assistant.cli.setup.restart' | tbAiSlots; track $index) {@if (part.slot === 'exit') {/exit} @else {{{ part.text }}}}

      +
      +

      {{ 'ai-assistant.cli.setup.come-back' | translate }}

      +
    20. + } +
    +
    +
    +
  2. +
  3. + +
    + {{ 'ai-assistant.cli.describe.title' | translate }} +

    {{ 'ai-assistant.cli.describe.text' | translate }}

    +
    + @for (item of builds; track item.id) { + + } +
    +
    +

    + {{ ('ai-assistant.cli.describe.' + build() + '.what') | translate }} + @if (buildLink(build()); as link) { + {{ ('ai-assistant.cli.describe.' + build() + '.link') | translate }} + } +

    +
    +
  4. +
  5. + +
    + {{ 'ai-assistant.cli.deploy.title' | translate }} +

    {{ 'ai-assistant.cli.deploy.text' | translate }}

    +

    {{ 'ai-assistant.cli.deploy.push-note' | translate }}

    +

    {{ 'ai-assistant.cli.deploy.stream' | translate }}

    +
    +
    +
  6. +
  7. + +
    + {{ 'ai-assistant.cli.connect-device.title' | translate }} +

    {{ 'ai-assistant.cli.connect-device.text' | translate }}

    +
    +
  8. +
+
+
+ + +
diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss new file mode 100644 index 0000000000..6e4184f6a0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss @@ -0,0 +1,1346 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '../../../components/ai/ai-code-blocks' as *; +@use '../../../components/ai/ai-icon-button' as *; + +$ease: cubic-bezier(.2, 0, 0, 1); +$motion: .15s; +$breathe: 2.4s; +$hero-bg: #1b252c; + +: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); + + a:hover, a:focus { + border-bottom: none; + } +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.ai-chat-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); + + &::after { + content: ''; + position: absolute; + left: 0; + right: 0; + top: 100%; + height: 12px; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); + opacity: 0; + transition: opacity $motion ease; + pointer-events: none; + } + + &.scrolled::after { + opacity: 1; + } + + @media (max-width: 599px) { + padding: 0 4px 0 8px; + } +} + +.ai-chat-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} + +:host ::ng-deep .ai-ib { + @include ai-icon-button; +} + +.ai-cli-scroll { + flex: 1; + min-height: 0; + overflow-x: hidden; + overflow-y: auto; + padding: 0 20px; + text-align: left; +} + +.ai-cli-hero { + position: relative; + overflow: hidden; + isolation: isolate; + container-type: inline-size; + margin: 0 -20px; + padding: 32px 20px; + background: $hero-bg; +} + +.ai-cli-ascii { + --free: calc(260px + max(200px, (100cqw - 680px) / 2)); + position: absolute; + top: -82px; + right: -260px; + z-index: -1; + width: max-content; + margin: 0; + padding: 0; + font: 400 11px/11px var(--tb-mono); + letter-spacing: 0.5px; + white-space: pre; + color: color-mix(in srgb, var(--ai-dark-accent-soft) 54%, transparent); + pointer-events: none; + user-select: none; + -webkit-mask-image: linear-gradient(270deg, #000 0, #000 var(--free), rgba(0, 0, 0, 0.7) calc(var(--free) + 140px), transparent calc(var(--free) + 420px)); + mask-image: linear-gradient(270deg, #000 0, #000 var(--free), rgba(0, 0, 0, 0.7) calc(var(--free) + 140px), transparent calc(var(--free) + 420px)); +} + +.ai-cli-hero-in { + max-width: 680px; + margin: 0 auto; +} + +.ai-cli-head { + display: grid; + grid-template-columns: 56px minmax(0, 1fr); + column-gap: 16px; + row-gap: 4px; + align-items: start; + + .ob-title { + grid-column: 2; + grid-row: 1; + margin: 0; + font: 500 24px/32px var(--tb-font); + letter-spacing: normal; + color: #fff; + text-align: left; + text-wrap: balance; + } + + .ob-lead { + grid-column: 2; + grid-row: 2; + margin: 0; + font-size: 16px; + line-height: 24px; + max-width: 56ch; + letter-spacing: 0.15px; + color: #b4bec6; + text-wrap: pretty; + } +} + +.ai-cli-tile { + position: relative; + overflow: hidden; + isolation: isolate; + grid-row: 1 / span 2; + width: 56px; + height: 56px; + border-radius: 16px; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--ai-dark-accent); + box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.18); + color: var(--ai-on-dark-accent); + + &::before { + content: ''; + position: absolute; + inset: 0 -100%; + z-index: -1; + background: linear-gradient(115deg, var(--ai-dark-accent-soft), var(--ai-dark-accent) 30%, var(--ai-dark-accent-pale) 50%, var(--ai-dark-accent) 70%, var(--ai-dark-accent-soft)); + animation: ai-cli-drift $breathe * 4 ease-in-out infinite alternate; + } + + .mat-icon { + font-size: 30px; + width: 30px; + height: 30px; + color: inherit; + } +} + +@keyframes ai-cli-drift { + from { + transform: translateX(-30%); + } + to { + transform: translateX(30%); + } +} + +.ai-cli-hero-set { + display: grid; + gap: 24px; + max-width: 680px; + margin: 20px auto 0; +} + +.ai-cli-acts { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 20px; + padding-left: 72px; +} + +.ai-cli-start { + display: inline-flex; + align-items: center; + gap: 6px; + height: 40px; + padding: 0 14px 0 18px; + border: 0; + border-radius: 10px; + background: var(--ai-dark-accent); + color: var(--ai-on-dark-accent); + font-family: inherit; + font-size: var(--chat-text); + font-weight: 500; + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: background-color $motion $ease; + + .mat-icon { + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); + color: inherit; + transition: transform $motion $ease; + } + + &:hover { + background: var(--ai-dark-accent-hover); + + .mat-icon { + transform: translateY(2px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; + } +} + +.ai-cli-slot { + display: contents; +} + +.ai-cli-alt { + display: inline-flex; + align-items: center; + gap: 4px; + height: 28px; + padding: 0; + border: 0; + background: none; + color: var(--ai-dark-accent); + font-family: inherit; + font-size: var(--chat-line); + font-weight: 500; + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: color $motion $ease; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } + + &, &:hover, &:focus { + border-bottom: 0; + text-decoration: none; + } + + &:is(a) { + letter-spacing: inherit; + } + + &:hover { + color: var(--ai-dark-accent-pale); + } + + &:hover > span:first-child { + text-decoration: underline; + text-underline-offset: 3px; + } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; + } +} + +.ai-cli { + max-width: 680px; + margin: 24px auto 0; + padding-bottom: 8px; + + :is(li, small) { + text-wrap: pretty; + } + + :is(h2, p, .ai-cli-body > b, .ai-cli-step-head > b, .ai-cli-subs > li > b), .ai-cli-flow > li > :is(b, p) { + text-wrap: balance; + } + + p { + letter-spacing: inherit; + } + + code { + padding: 1px 5px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.05); + font-family: var(--tb-mono); + font-size: 13px; + color: var(--tb-ink); + } +} + +.ai-sec { + margin-top: 36px; +} + +.ai-sec-head { + h2 { + margin: 0; + font: 500 20px/28px var(--tb-font); + letter-spacing: -0.1px; + color: var(--tb-ink); + } + + p { + max-width: 620px; + margin: 2px 0 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink-60); + } +} + +.ai-cli-flow { + list-style: none; + margin: 14px 0 0; + padding: 0; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 16px; + + > li { + display: grid; + align-content: start; + gap: 4px; + min-width: 0; + + > b { + margin-top: 8px; + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + font-weight: 500; + color: var(--tb-ink); + } + + > p { + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-60); + } + } + + @media (max-width: 639px) { + grid-template-columns: minmax(0, 1fr); + gap: 24px; + } +} + +.ai-cli-pic { + height: 120px; + box-sizing: border-box; + min-width: 0; + padding: 0 16px; + border-radius: 14px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + overflow: hidden; + display: grid; + align-content: center; + + &.agents { + grid-auto-flow: column; + justify-content: center; + gap: 16px; + } +} + +.ai-cli-logo { + display: grid; + place-items: center; + width: 64px; + height: 64px; + border: 0; + border-radius: 18px; + background: var(--tb-surface); + box-shadow: 0 1px 3px color-mix(in srgb, var(--glow) 16%, transparent), 0 12px 26px -8px color-mix(in srgb, var(--glow) 46%, transparent); + animation: ai-cli-rise $breathe ease-in-out infinite alternate; + + & + .ai-cli-logo { + animation-delay: -1.2s; + } + + img { + display: block; + width: 34px; + height: 34px; + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 4px; + } +} + +.ai-cli-tree { + display: grid; + min-width: 0; + font-family: var(--tb-mono); + font-size: 12.5px; + font-weight: 500; + line-height: 20px; + color: var(--tb-ink); + + .commit { + display: flex; + align-items: center; + gap: 6px; + height: 20px; + min-width: 0; + margin-bottom: 6px; + font-size: var(--chat-meta); + font-weight: 400; + white-space: nowrap; + color: var(--tb-ink-54); + + .mat-icon { + flex: none; + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + color: var(--ai-selected); + } + + b { + flex: none; + font-weight: 500; + color: var(--ai-selected); + } + + > span:last-child { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + } + + .row { + position: relative; + display: flex; + align-items: center; + gap: 6px; + height: 20px; + min-width: 0; + padding-left: calc(var(--d) * 18px); + white-space: nowrap; + + > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + + .mat-icon { + flex: none; + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + color: var(--tb-ink-54); + + &.tone-device { + color: var(--entity-device-fg); + } + + &.tone-view { + color: var(--entity-view-fg); + } + + &.tone-rule { + color: var(--entity-rule-fg); + } + } + + &:not(.top)::before { + content: ''; + position: absolute; + left: calc((var(--d) - 1) * 18px + 7px); + top: 10px; + width: 9px; + border-top: 1px solid var(--k-stroke-hover); + } + + &:not(.top):not(.last)::after { + content: ''; + position: absolute; + left: calc((var(--d) - 1) * 18px + 7px); + top: 0; + bottom: 0; + border-left: 1px solid var(--k-stroke-hover); + } + + &.last:not(.top)::before { + top: 0; + height: 11px; + box-sizing: border-box; + border-top: 0; + border-left: 1px solid var(--k-stroke-hover); + border-bottom: 1px solid var(--k-stroke-hover); + border-bottom-left-radius: 5px; + } + + &.first:not(.last)::after, &.first.last::before { + top: -1px; + } + + &.first.last::before { + height: 12px; + } + } +} + +.ai-cli-ask { + display: grid; + gap: 2px; + min-width: 0; + font-family: var(--tb-mono); + font-size: 12.5px; + font-weight: 500; + line-height: 18px; + color: var(--tb-ink-76); + + .chk { + display: grid; + grid-template-columns: 12px minmax(0, 1fr); + gap: 4px; + margin-bottom: 4px; + font-weight: 400; + color: var(--tb-ink-54); + + > i { + font-style: normal; + color: var(--ai-selected); + } + } + + .q { + margin-bottom: 2px; + font-weight: 600; + color: var(--tb-ink); + } + + .opt { + display: grid; + grid-template-columns: 12px minmax(0, 1fr) auto; + gap: 4px; + margin: 0 -6px; + padding: 2px 6px; + border-radius: 6px; + + > i { + font-style: normal; + color: var(--ai-selected); + animation: ai-cli-lit $breathe ease-in-out infinite alternate; + } + + .enter { + color: var(--ai-selected); + opacity: 0.7; + } + + &.on { + background: var(--ai-selected-wash); + color: var(--ai-selected-text); + } + } +} + +@keyframes ai-cli-rise { + from { + transform: translateY(2px); + } + to { + transform: translateY(-3px); + } +} + +@keyframes ai-cli-lit { + from { + opacity: 0.4; + } + to { + opacity: 1; + } +} + +#ai-cli-steps { + margin-top: 40px; + padding-top: 36px; + border-top: 1px solid var(--k-stroke); +} + +.ai-cli-steps { + list-style: none; + margin: 4px 0 0; + padding: 0; + display: grid; +} + +.ai-cli-step { + position: relative; + display: grid; + grid-template-columns: 44px minmax(0, 1fr); + gap: 16px; + padding: 20px 0; + + & + .ai-cli-step { + border-top: 1px solid var(--k-stroke); + } +} + +.ai-cli-n { + position: relative; + z-index: 1; + width: 44px; + height: 44px; + border-radius: 13px; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--ai-selected-wash); + color: var(--ai-selected-text); + + .mat-icon { + font-size: 24px; + width: 24px; + height: 24px; + color: var(--ai-selected-text); + } +} + +.ai-cli-body { + min-width: 0; + padding-top: 8px; + + > b { + display: block; + font-size: 18px; + line-height: 28px; + font-weight: 500; + color: var(--tb-ink); + } + + > p { + margin: 6px 0 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink-76); + } + + > .ai-cli-note { + margin-top: 8px; + } + + > .ai-cli-step-head + .ai-cli-setup { + margin-top: 14px; + } +} + +.ai-cli-step-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 16px; + margin: -2px 0; + + > b { + font-size: 18px; + line-height: 28px; + font-weight: 500; + color: var(--tb-ink); + } +} + +.ai-cli-ways { + display: inline-flex; + max-width: 100%; + height: 32px; + box-sizing: border-box; + padding: 2px; + border-radius: 100px; + background: rgba(0, 0, 0, 0.06); + + .tb-toggle-option { + position: relative; + flex: 1 1 auto; + height: 28px; + padding: 0 12px; + border: 0; + border-radius: 20px; + background: none; + font-family: inherit; + font-size: var(--chat-line); + line-height: 28px; + letter-spacing: 0.2px; + white-space: nowrap; + text-align: center; + color: var(--tb-text-muted); + cursor: pointer; + transition: color $motion $ease; + + &:hover { + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--tb-surface); + color: var(--tb-ink); + font-weight: 500; + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.10), 0 1px 4px rgba(16, 24, 40, 0.06); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + } +} + +.ai-cli-subs { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 16px; + counter-reset: sub; + + > li { + position: relative; + display: grid; + gap: 6px; + min-width: 0; + padding-left: 34px; + counter-increment: sub; + + &::before { + content: counter(sub); + position: absolute; + left: 0; + top: 1px; + width: 22px; + height: 22px; + box-sizing: border-box; + display: grid; + place-items: center; + border-radius: 50%; + box-shadow: inset 0 0 0 1px var(--k-stroke-hover); + font-size: 12px; + font-weight: 500; + line-height: 1; + color: var(--tb-ink-76); + } + + &:not(:last-child)::after { + content: ''; + position: absolute; + left: 10.5px; + top: 27px; + bottom: -13px; + width: 1px; + background: var(--k-stroke); + } + + > b { + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + font-weight: 500; + color: var(--tb-ink); + } + + > p { + margin: 0; + font-size: 15px; + line-height: 22px; + color: var(--tb-ink-76); + } + + > .ai-cli-keys { + justify-self: start; + } + } +} + +.ai-cli-keys { + height: 36px; + border-color: var(--k-stroke); + color: var(--tb-ink-76); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.ai-cli-nb { + white-space: nowrap; +} + +.ai-cli-picks { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 10px; +} + +.ai-cli-pick { + height: 30px; + padding: 0 12px; + border: 0; + border-radius: 100px; + background: none; + box-shadow: inset 0 0 0 1px var(--k-stroke-hover); + color: var(--tb-ink-76); + font-family: inherit; + font-size: var(--chat-chip); + font-weight: 500; + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: background-color $motion $ease, box-shadow $motion $ease; + + &:hover { + box-shadow: inset 0 0 0 1px var(--tb-ink-38); + } + + &[aria-pressed="true"] { + background: var(--ai-selected-wash); + box-shadow: inset 0 0 0 1px var(--ai-selected); + color: var(--ai-selected-text); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } +} + +.ai-cli-body > .ai-cli-what { + margin: 10px 0 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink-76); + + a { + color: var(--ai-link); + } +} + +.ai-cli-end { + margin: 36px -20px 0; + padding: 28px 20px 32px; + background: $hero-bg; + + h2 { + margin: 0; + font: 500 16px/22px var(--tb-font); + color: #fff; + } +} + +.ai-cli-end-in { + max-width: 680px; + margin: 0 auto; +} + +.ai-cli-links { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; + margin-top: 14px; + + @media (max-width: 699px) { + grid-template-columns: 1fr; + } +} + +.ai-cli-link { + display: grid; + grid-template-columns: 20px minmax(0, 1fr) 16px; + gap: 10px; + align-items: start; + padding: 12px 12px 14px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.05); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1); + color: inherit; + text-decoration: none; + transition: background-color $motion ease, box-shadow $motion ease; + + &, &:hover, &:focus, &:focus-visible { + border-bottom: 0; + text-decoration: none; + } + + > .mat-icon:first-child { + font-size: 20px; + width: 20px; + height: 20px; + color: var(--ai-dark-accent); + } + + b { + display: block; + font: 500 14px/20px var(--tb-font); + color: #fff; + text-wrap: balance; + } + + small { + display: block; + margin-top: 2px; + font-size: 12.5px; + line-height: 17px; + color: #9fadb7; + text-wrap: balance; + } + + .ai-cli-go { + font-size: 16px; + width: 16px; + height: 16px; + color: #7d8c96; + transition: transform $motion ease, color $motion ease; + } + + &:hover { + background: rgba(255, 255, 255, 0.09); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ai-dark-accent) 40%, transparent); + + small { + color: #b4bec6; + } + + .ai-cli-go { + color: #fff; + transform: translate(1px, -1px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent); + outline-offset: 2px; + } +} + +:host ::ng-deep .ai-cli-scroll { + @include ai-code-blocks; + + .ai-cli .tb-codeblock { + margin-top: 12px; + } + + .ai-cli .tb-cmdrow { + margin-top: 10px; + } + + .ai-cli-term { + --term-bg: color-mix(in srgb, #{$hero-bg} 58%, #000); + --term-fg: var(--tb-code-fg); + --term-text: #9fadb7; + --term-muted: #7d8c96; + --term-faint: #5f6f7a; + --term-hover: #b4bec6; + --term-rule: rgba(255, 255, 255, 0.07); + --term-art: linear-gradient(90deg in oklab, var(--ai-dark-accent), var(--ai-light-lilac), var(--ai-light-peach)); + min-width: 0; + + .banner { + display: grid; + color: var(--term-muted); + + .art { + justify-self: start; + max-width: 100%; + margin-bottom: 10px; + overflow: hidden; + white-space: pre; + font-size: 12px; + line-height: 13px; + color: var(--ai-dark-accent-soft); + } + + b { + font-weight: 500; + color: var(--term-fg); + } + + i { + font-style: normal; + color: var(--ai-dark-accent); + } + } + + .r { + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + min-width: 0; + overflow-wrap: anywhere; + + > i { + font-style: normal; + color: var(--ai-dark-accent); + } + + &.past { + opacity: 0.5; + } + + &.think { + color: var(--term-muted); + + > i { + display: inline-block; + transform: scale(1.5); + transform-origin: 30% 55%; + } + + &.done > i { + color: var(--term-faint); + } + } + + &.out.run .t { + color: var(--term-faint); + } + + &:is(.you, .tool, .say, .think) { + margin-top: var(--chat-line-lh); + } + + &.you { + color: #fff; + } + + &:is(.tool, .say, .ask) { + color: var(--term-fg); + } + + &.tool b { + font-weight: 500; + color: var(--ai-dark-accent); + } + + &:is(.out, .ok, .ask) { + padding-left: 2ch; + } + + &.out > i { + color: var(--term-faint); + } + + &.say > i { + color: #fff; + } + } + + .caret { + display: inline-block; + width: 1ch; + height: 1.15em; + vertical-align: text-bottom; + background: var(--ai-dark-accent); + animation: ai-cli-lit $breathe ease-in-out infinite alternate; + + &.typing { + animation: none; + } + } + } + + @supports ((background-clip: text) or (-webkit-background-clip: text)) { + .ai-cli-term .banner .art { + background: var(--term-art); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + } + + @media (forced-colors: active) { + .ai-cli-term .banner .art { + background: none; + color: CanvasText; + } + } + + .ai-cli-term-bar { + display: flex; + align-items: flex-end; + min-width: 0; + + .dots { + flex: none; + display: flex; + gap: 6px; + margin: 0 4px 12px 14px; + + i { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.1); + } + } + + .tabs { + display: flex; + gap: 2px; + min-width: 0; + padding: 0 18px 0 10px; + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + } + + [role="tab"] { + position: relative; + flex: none; + height: 32px; + padding: 0 14px; + border: 0; + border-radius: 8px 8px 0 0; + background: none; + color: var(--term-muted); + font-family: var(--tb-mono); + font-size: var(--chat-meta); + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: color $motion $ease; + + &:hover { + background: rgba(255, 255, 255, 0.04); + color: var(--term-hover); + } + + &[aria-selected="true"] { + background: var(--term-bg); + color: var(--term-fg); + + &::before, &::after { + content: ''; + position: absolute; + bottom: 0; + width: 8px; + height: 8px; + pointer-events: none; + } + + &::before { + left: -8px; + background: radial-gradient(circle at 0 0, transparent 8px, var(--term-bg) 8.5px); + } + + &::after { + right: -8px; + background: radial-gradient(circle at 100% 0, transparent 8px, var(--term-bg) 8.5px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: -2px; + } + } + } + + .ai-cli-term-body { + height: 268px; + display: flex; + flex-direction: column; + border-radius: 10px; + background: var(--term-bg); + box-shadow: 0 18px 40px -18px rgba(0, 0, 0, 0.55); + overflow: hidden; + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; + } + } + + .ai-cli-term-view { + flex: 1; + min-height: 0; + box-sizing: border-box; + padding: 12px 16px 10px; + display: flex; + flex-direction: column; + overflow: hidden; + + &.full { + justify-content: flex-end; + -webkit-mask-image: linear-gradient(transparent, #000 30px); + mask-image: linear-gradient(transparent, #000 30px); + } + } + + .ai-cli-term-rows { + display: grid; + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--term-text); + transition: opacity .24s cubic-bezier(.05, .7, .1, 1); + + > .r:first-child { + margin-top: 0; + } + + &.out { + opacity: 0; + transition: opacity .16s cubic-bezier(.3, 0, .8, .15); + } + } + + .ai-cli-term-input { + flex: none; + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + padding: 10px 16px 12px; + box-shadow: inset 0 1px 0 var(--term-rule); + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: #fff; + overflow-wrap: anywhere; + + > i { + font-style: normal; + color: var(--ai-dark-accent); + } + + &.menu .t { + display: grid; + } + + .opt { + color: var(--term-muted); + + &.on { + color: var(--ai-dark-accent); + } + + &.press { + color: var(--ai-dark-accent-pale); + } + } + } + + @container (min-width: 640px) { + .ai-cli-term { + width: 100%; + max-width: 600px; + margin-left: 72px; + box-sizing: border-box; + } + } + + @container (max-width: 639px) { + .ai-cli-term-bar { + .dots { + display: none; + } + + .tabs { + padding: 0 10px; + } + } + + .ai-cli-term .banner .art { + font-size: 9.5px; + line-height: 10px; + } + } + + @media (prefers-reduced-motion: reduce) { + .ai-cli-term .caret, .ai-cli-term-rows { + animation: none; + transition: none; + } + } +} + +@container (max-width: 480px) { + .ai-cli-start .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +@media (max-width: 720px) { + .ai-cli-head .ob-title { + font-size: 22px; + line-height: 28px; + } +} + +@media (prefers-reduced-motion: reduce) { + .ai-cli-tile::before, .ai-cli-logo, .ai-cli-ask .opt > i { + animation: none; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts new file mode 100644 index 0000000000..519acf3895 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts @@ -0,0 +1,259 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterNextRender, + afterRenderEffect, + ChangeDetectionStrategy, + Component, + DestroyRef, + ElementRef, + inject, + Injector, + NgZone, + output, + signal +} from '@angular/core'; +import { Router } from '@angular/router'; +import { TranslateService } from '@ngx-translate/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { + codeTabGroup, + codeTabsBlock, + commandRow, + labelledCodeBlock, + onCodeTabGroup, + valueBlock +} from '@home/components/ai/ai-code-block'; +import { + asciiGlobe, + CLI_AGENT_GROUP, + CLI_AGENTS, + CLI_BUILDS, + CLI_DOCS, + CLI_DOCS_LINKS, + CLI_INSTALL, + CLI_OS_GROUP, + CliAgentInfo, + CliBuild, + cliOs, + CliOs, + CliWay +} from '@home/pages/ai-assistant/cli/ai-cli.models'; +import { writeStored } from '@core/local-storage/stored'; +import { cliTerm, CliTerm } from '@home/pages/ai-assistant/cli/ai-cli-term'; + +interface CliPicks { + way?: CliWay; + build?: CliBuild; +} + +interface CliTreeRow { + depth: number; + name: string; + last: boolean; + first: boolean; + icon: string; + tone?: string; +} + +@Component({ + selector: 'tb-ai-cli-guide', + templateUrl: './ai-cli-guide.component.html', + styleUrls: ['./ai-cli-guide.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false, + host: { + 'data-ai': '', + 'class': 'tb-ai-cli-guide' + } +}) +export class AiCliGuideComponent { + + private static readonly PICKS_KEY = 'tb-ai-cli'; + + closed = output(); + + readonly docs = CLI_DOCS; + + readonly agents = CLI_AGENTS; + + readonly builds = CLI_BUILDS; + + readonly links = CLI_DOCS_LINKS; + + readonly ways: CliWay[] = ['agent', 'terminal']; + + readonly globe = asciiGlobe(36, 210, 160, 9, 24); + + readonly url = window.location.origin; + + readonly tree: CliTreeRow[] = [ + {depth: 0, name: 'smart-retail', last: true, first: false, icon: 'folder'}, + {depth: 1, name: 'devices', last: false, first: true, icon: 'memory', tone: 'device'}, + {depth: 1, name: 'dashboards', last: false, first: false, icon: 'dashboard', tone: 'view'}, + {depth: 1, name: 'alarm-rules', last: true, first: false, icon: 'rule', tone: 'rule'} + ]; + + private readonly picks = AiCliGuideComponent.readPicks(); + + way = signal(this.picks.way === 'terminal' ? 'terminal' : 'agent'); + + build = signal(CLI_BUILDS.some(item => item.id === this.picks.build) ? this.picks.build : 'sensor'); + + os = signal(AiCliGuideComponent.storedOs()); + + fullscreen = signal(false); + + scrolled = signal(false); + + private translate = inject(TranslateService); + private clipboard = inject(ClipboardService); + private router = inject(Router); + private injector = inject(Injector); + private host = inject>(ElementRef); + private zone = inject(NgZone); + private term: CliTerm | null = null; + + readonly hostElement = this.host.nativeElement; + + constructor() { + const stop = onCodeTabGroup(CLI_OS_GROUP, id => this.os.set(id === 'windows' ? 'windows' : 'unix')); + inject(DestroyRef).onDestroy(() => { + stop(); + this.term?.destroy(); + }); + afterRenderEffect(() => { + this.way(); + this.build(); + this.os(); + this.fillSlots(); + }); + } + + pickWay(way: CliWay, event: Event): void { + if (way === this.way()) { + return; + } + const control = event.currentTarget as HTMLElement; + const top = control.getBoundingClientRect().top; + this.way.set(way); + this.savePicks(); + afterNextRender(() => { + const scroller = this.scroller(); + if (scroller && control.isConnected) { + scroller.scrollTop += control.getBoundingClientRect().top - top; + control.focus({preventScroll: true}); + } + }, {injector: this.injector}); + } + + pickBuild(build: CliBuild): void { + this.build.set(build); + this.savePicks(); + } + + toSteps(): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + this.hostElement.querySelector('#ai-cli-steps')?.scrollIntoView({behavior: reduce ? 'auto' : 'smooth', block: 'start'}); + } + + openApiKeys(): void { + this.router.navigate(['/account/security']); + } + + toggleFullscreen(): void { + this.fullscreen.set(!this.fullscreen()); + } + + onScroll(scroller: HTMLElement): void { + this.scrolled.set(scroller.scrollTop > 0); + } + + buildLink(build: CliBuild): string | null { + const link = CLI_BUILDS.find(item => item.id === build)?.link; + return link ? CLI_DOCS + link : null; + } + + private scroller(): HTMLElement | null { + return this.hostElement.querySelector('.ai-cli-scroll'); + } + + private fillSlots(): void { + this.hostElement.querySelectorAll('.ai-cli-slot').forEach(slot => { + const key = slot.dataset.kind + ':' + (slot.dataset.key ?? ''); + if (slot.dataset.built !== key) { + slot.dataset.built = key; + slot.replaceChildren(this.blockFor(slot.dataset.kind, slot.dataset.key)); + } + }); + } + + private blockFor(kind: string, key: string | undefined): HTMLElement { + const copy = (text: string) => this.clipboard.copyFromContent(text); + const say = (word: string) => this.translate.instant('ai-assistant.cli.' + word); + switch (kind) { + case 'term': + return this.termBlock(); + case 'install': + return this.installBlock(); + case 'prompt': + return labelledCodeBlock(say('setup-prompt'), say('setup-prompt-label'), 'text', this.translate, copy, + {check: true, classes: 'wrap'}); + case 'url': + return valueBlock(say('setup.url'), this.url, this.translate, copy, say('setup.copy-url')); + case 'agent-start': + return this.agentBlock(agent => `mkdir thingsboard-project && cd thingsboard-project && ${agent.run}`); + case 'agent-return': + return this.agentBlock(agent => `cd thingsboard-project && ${agent.run}`); + case 'agent-restart': + return this.agentBlock(agent => agent.restart); + case 'build': + return labelledCodeBlock(CLI_BUILDS.find(item => item.id === key)?.prompt ?? '', say('describe.prompt'), 'text', this.translate, copy, + {check: true, classes: 'wrap'}); + case 'emulator': + return commandRow('tb emulator run --duration 5m', key === 'windows', this.translate, copy); + default: + return document.createElement('span'); + } + } + + private termBlock(): HTMLElement { + this.term?.destroy(); + this.term = this.zone.runOutsideAngular(() => cliTerm((key, params) => this.translate.instant(key, params))); + return this.term.element; + } + + private installBlock(): HTMLElement { + return codeTabsBlock([ + {id: 'unix', label: this.translate.instant('ai-assistant.cli.mac-linux'), text: CLI_INSTALL.unix, lang: 'shell'}, + {id: 'windows', label: this.translate.instant('ai-assistant.cli.windows'), text: CLI_INSTALL.windows, lang: 'powershell'} + ], 'shell', this.translate, text => this.clipboard.copyFromContent(text), this.os() === 'windows' ? 1 : 0, + tab => this.os.set(tab.id === 'windows' ? 'windows' : 'unix'), + {group: CLI_OS_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, check: true}); + } + + private agentBlock(text: (agent: CliAgentInfo) => string): HTMLElement { + return codeTabsBlock(this.agents.map(agent => ({id: agent.id, label: agent.name, text: text(agent), lang: 'shell'})), + 'shell', this.translate, value => this.clipboard.copyFromContent(value), 0, undefined, + {group: CLI_AGENT_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, check: true}); + } + + private savePicks(): void { + const picks: CliPicks = {way: this.way(), build: this.build()}; + writeStored(AiCliGuideComponent.PICKS_KEY, JSON.stringify(picks)); + } + + private static readPicks(): CliPicks { + try { + const stored = localStorage.getItem(AiCliGuideComponent.PICKS_KEY); + return stored ? JSON.parse(stored) ?? {} : {}; + } catch { + return {}; + } + } + + private static storedOs(): CliOs { + const stored = codeTabGroup(CLI_OS_GROUP); + return stored === 'windows' || stored === 'unix' ? stored : cliOs(); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts new file mode 100644 index 0000000000..0b20f12b7b --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + CLI_ART, + CLI_TERM_HOLD, + CLI_TERM_SESSIONS, + CLI_TERM_WAIT, + CLI_VERSION, + CliTermRow, + CliTermSession +} from '@home/pages/ai-assistant/cli/ai-cli.models'; + +export interface CliTerm { + element: HTMLElement; + destroy: () => void; +} + +const MARK: Record = {you: '❯', tool: '●', out: '└', say: '●', ok: '✔', ask: '', think: '⠿'}; +const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'; + +let shownTab = 0; +let turning = true; +let termCount = 0; + +type Kid = Node | string | null; + +function el(tag: string, cls?: string, ...kids: Kid[]): HTMLElement { + const node = document.createElement(tag); + if (cls) { + node.className = cls; + } + kids.forEach(kid => { + if (kid != null) { + node.append(kid); + } + }); + return node; +} + +const jitter = (lo: number, hi: number) => lo + Math.random() * (hi - lo); + +export function cliTerm(say: (key: string, params?: Record) => string): CliTerm { + const calm = matchMedia('(prefers-reduced-motion: reduce)').matches; + const uid = 'ai-cli-term-' + (++termCount); + const t = (key: string) => say('ai-assistant.cli.term.' + key); + const list = el('div', 'ai-cli-term-rows'); + list.setAttribute('role', 'img'); + const view = el('div', 'ai-cli-term-view', list); + const typed = document.createTextNode(''); + const caret = el('span', 'caret'); + const line = el('span', 't', typed, caret); + const input = el('div', 'ai-cli-term-input', el('i', null, '❯'), line); + input.setAttribute('aria-hidden', 'true'); + const body = el('div', 'ai-cli-term-body', view, input); + body.setAttribute('role', 'tabpanel'); + body.id = uid + '-panel'; + body.tabIndex = 0; + const touch = () => { + turning = false; + }; + const pickTab = (k: number) => { + touch(); + if (k !== shownTab) { + play(k); + } + }; + const tabs = CLI_TERM_SESSIONS.map((session, k) => { + const tab = el('button', null, session.tab) as HTMLButtonElement; + tab.type = 'button'; + tab.setAttribute('role', 'tab'); + tab.id = `${uid}-tab-${k}`; + tab.setAttribute('aria-controls', body.id); + tab.addEventListener('click', () => pickTab(k)); + return tab; + }); + const strip = el('div', 'tabs', ...tabs); + strip.setAttribute('role', 'tablist'); + strip.setAttribute('aria-label', t('label')); + strip.addEventListener('keydown', (event: KeyboardEvent) => { + const k = tabs.indexOf(document.activeElement as HTMLButtonElement); + const n = tabs.length; + const to = ({ArrowRight: k + 1, ArrowLeft: k - 1 + n, Home: 0, End: n - 1} as Record)[event.key]; + if (k < 0 || to == null) { + return; + } + event.preventDefault(); + pickTab(to % n); + tabs[to % n].focus(); + }); + const dots = el('span', 'dots', el('i'), el('i'), el('i')); + dots.setAttribute('aria-hidden', 'true'); + const root = el('div', 'ai-cli-term', el('div', 'ai-cli-term-bar', dots, strip), body); + root.addEventListener('click', touch); + + let run = 0; + let spin: ReturnType | null = null; + let thinking: HTMLElement | null = null; + let t0 = 0; + let seen = true; + let hover = false; + let started = false; + let told = false; + let io: IntersectionObserver | null = null; + let fallback: ReturnType | null = null; + const timers = new Set>(); + + const later = (ms: number, fn: () => void) => { + const r = run; + const id = setTimeout(() => { + timers.delete(id); + if (r === run && root.isConnected) { + fn(); + } + }, ms); + timers.add(id); + }; + const stopSpin = () => { + if (spin) { + clearInterval(spin); + spin = null; + } + }; + const setInput = (text: string) => { + typed.data = text; + line.replaceChildren(typed, caret); + input.classList.remove('menu'); + caret.classList.toggle('typing', !!text); + }; + const stop = () => { + run += 1; + timers.forEach(clearTimeout); + timers.clear(); + stopSpin(); + thinking = null; + setInput(''); + }; + const fit = () => { + const room = view.clientHeight; + if (room) { + view.classList.toggle('full', list.offsetHeight > room - 16); + } + }; + const row = (kind: string, ...kids: Kid[]) => { + const r = el('span', 'r ' + kind, el('i', null, MARK[kind.split(' ')[0]]), el('span', 't', ...kids)); + list.insertBefore(r, thinking); + fit(); + return r; + }; + const toolRow = (item: CliTermRow) => row('tool', el('b', null, item.tool), `(${item.arg})`); + const think = () => { + t0 = Date.now(); + thinking = el('span', 'r think', el('i', null, SPIN[0]), el('span', 't', t('thinking'))); + list.append(thinking); + fit(); + let f = 0; + const glyph = thinking.firstChild as HTMLElement; + spin = setInterval(() => { + if (!root.isConnected) { + stopSpin(); + return; + } + f += 1; + glyph.textContent = SPIN[f % SPIN.length]; + }, 90); + }; + const done = () => { + if (!thinking) { + return; + } + stopSpin(); + thinking.classList.add('done'); + thinking.firstChild.textContent = '⠿'; + thinking.lastChild.textContent = say('ai-assistant.cli.term.done', {seconds: Math.max(1, Math.round((Date.now() - t0) / 1000))}); + thinking = null; + }; + const send = (text: string, next: () => void) => { + setInput(''); + row('you', text); + think(); + later(jitter(900, 1500), next); + }; + const type = (text: string, next: () => void) => { + let n = 0; + const tick = () => { + n += 1; + typed.data = text.slice(0, n); + caret.classList.add('typing'); + const ch = text[n - 1]; + if (n < text.length) { + later(ch === ' ' ? jitter(45, 120) : /[.,:]/.test(ch) ? jitter(140, 280) : jitter(30, 75), tick); + } else { + later(420, () => send(text, next)); + } + }; + tick(); + }; + const pick = (options: string[], next: () => void) => { + input.classList.add('menu'); + line.replaceChildren(...options.map((option, j) => el('span', 'opt' + (j ? '' : ' on'), `${j + 1}. ${option}`))); + later(1400, () => { + (line.firstChild as HTMLElement).classList.add('press'); + later(240, () => send(options[0], next)); + }); + }; + const stream = (node: HTMLElement, text: string, next: () => void) => { + const words = text.split(' '); + let n = 0; + const tick = () => { + n = Math.min(words.length, n + 1 + Math.floor(Math.random() * 3)); + node.textContent = words.slice(0, n).join(' '); + fit(); + if (n < words.length) { + later(jitter(45, 100), tick); + } else { + next(); + } + }; + tick(); + }; + const step = (rows: CliTermRow[], i: number) => { + if (i >= rows.length) { + done(); + if (turning) { + later(CLI_TERM_HOLD, advance); + } + return; + } + const item = rows[i]; + const go = () => later(CLI_TERM_WAIT[(rows[i + 1] ?? {kind: 'you'}).kind], () => step(rows, i + 1)); + if (item.kind === 'you') { + done(); + type(t(item.text), () => step(rows, i + 1)); + return; + } + if (item.kind === 'pick') { + done(); + pick(item.options.map(t), () => step(rows, i + 1)); + return; + } + if (item.kind === 'tool') { + toolRow(item); + go(); + return; + } + if (item.kind === 'out') { + const r = row('out run', t('running')); + later(item.ms || 1200, () => { + r.classList.remove('run'); + r.lastChild.textContent = t(item.text); + fit(); + go(); + }); + return; + } + stream(row(item.kind).lastChild as HTMLElement, t(item.text), go); + }; + const advance = () => { + if (!turning) { + return; + } + if (hover || !seen || document.hidden) { + later(600, advance); + return; + } + play((shownTab + 1) % CLI_TERM_SESSIONS.length); + }; + const intro = (session: CliTermSession) => { + if (session.banner) { + list.append(el('div', 'banner', el('span', 'art', CLI_ART), el('b', null, CLI_VERSION), + el('span', null, el('i', null, '✔'), ' ' + t('connected')), el('span', null, el('i', null, '✔'), ' ' + t('detected')))); + fit(); + return; + } + (session.intro ?? []).forEach(item => { + const r = item.kind === 'done' ? row('think done', say('ai-assistant.cli.term.done', {seconds: item.seconds})) + : item.kind === 'tool' ? toolRow(item) : row(item.kind, t(item.text)); + r.classList.add('past'); + }); + }; + const still = (rows: CliTermRow[]) => rows.forEach(item => { + if (item.kind === 'tool') { + toolRow(item); + } else if (item.kind === 'pick') { + row('you', t(item.options[0])); + } else { + row(item.kind, t(item.text)); + } + }); + const mark = (k: number) => { + shownTab = k; + tabs.forEach((tab, j) => { + tab.setAttribute('aria-selected', String(j === k)); + tab.tabIndex = j === k ? 0 : -1; + }); + if (strip.scrollWidth > strip.clientWidth) { + strip.scrollLeft += tabs[k].getBoundingClientRect().left - strip.getBoundingClientRect().left - 10; + } + body.setAttribute('aria-labelledby', tabs[k].id); + list.setAttribute('aria-label', say('ai-assistant.cli.term.picture', {about: t(CLI_TERM_SESSIONS[k].tab + '.about')})); + }; + const opening = (k: number) => { + list.replaceChildren(); + view.classList.remove('full'); + intro(CLI_TERM_SESSIONS[k]); + if (calm) { + still(CLI_TERM_SESSIONS[k].rows); + } + }; + const begin = (k: number) => later(CLI_TERM_WAIT.you, () => step(CLI_TERM_SESSIONS[k].rows, 0)); + function play(k: number): void { + stop(); + mark(k); + started = true; + const go = () => { + list.classList.remove('out'); + opening(k); + if (!calm) { + begin(k); + } + }; + if (list.firstChild && !calm) { + list.classList.add('out'); + later(260, go); + } else { + go(); + } + } + const refit = () => { + if (root.isConnected) { + fit(); + } + }; + + shownTab = Math.min(shownTab, CLI_TERM_SESSIONS.length - 1); + mark(shownTab); + opening(shownTab); + requestAnimationFrame(refit); + const destroy = () => { + stop(); + io?.disconnect(); + if (fallback) { + clearTimeout(fallback); + } + }; + if (calm) { + return {element: root, destroy}; + } + root.addEventListener('pointerenter', (event: PointerEvent) => { + if (event.pointerType === 'mouse') { + hover = true; + } + }); + root.addEventListener('pointerleave', () => { + hover = false; + }); + const start = () => { + if (!started) { + started = true; + begin(shownTab); + } + }; + if ('IntersectionObserver' in window) { + io = new IntersectionObserver(entries => { + told = true; + seen = entries[entries.length - 1].isIntersecting; + if (seen) { + start(); + } + }, {threshold: 0.2}); + io.observe(root); + } + fallback = setTimeout(() => { + fallback = null; + if (!told && root.isConnected) { + seen = true; + start(); + } + }, 1500); + return {element: root, destroy}; +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli.models.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli.models.ts new file mode 100644 index 0000000000..b8651dcee3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli.models.ts @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export type CliOs = 'unix' | 'windows'; + +export type CliAgent = 'claude' | 'antigravity'; + +export type CliWay = 'terminal' | 'agent'; + +export type CliBuild = 'sensor' | 'solution' | 'change'; + +export const CLI_OS_GROUP = 'cli-os'; + +export const CLI_AGENT_GROUP = 'cli-agent'; + +export const CLI_DOCS = 'https://thingsboard.io/docs/cli/'; + +export const CLI_INSTALL: Record = { + unix: 'curl -LsSf https://thingsboard.io/cli/install.sh | sh', + windows: 'powershell -ExecutionPolicy ByPass -c "irm https://thingsboard.io/cli/install.ps1 | iex"' +}; + +export interface CliAgentInfo { + id: CliAgent; + name: string; + run: string; + restart: string; + get: string; + glow: string; +} + +export const CLI_AGENTS: CliAgentInfo[] = [ + {id: 'claude', name: 'Claude Code', run: 'claude', restart: 'claude --continue', get: 'https://claude.com/claude-code', glow: '#D97757'}, + {id: 'antigravity', name: 'Antigravity', run: 'agy', restart: 'agy', get: 'https://antigravity.google/', glow: '#3186FF'} +]; + +export interface CliBuildInfo { + id: CliBuild; + prompt: string; + link?: string; +} + +export const CLI_BUILDS: CliBuildInfo[] = [ + { + id: 'sensor', + prompt: 'My office has a sensor that sends {"temperature": 22.5, "humidity": 41, "co2": 650} every minute. ' + + 'Create the device and a dashboard. Alert me when CO2 goes above 1000.' + }, + { + id: 'solution', + prompt: 'Create a smart retail solution for my supermarket chain: three stores, each with refrigeration, ambient and door sensors, ' + + 'an admin for the chain, a manager for each store, and alarms for the freezers.', + link: 'guides/example-smart-retail/' + }, + { + id: 'change', + prompt: 'Each freezer in my stores needs its own alarm limit. Let me set the limit from the dashboard.', + link: 'guides/alarms/' + } +]; + +export interface CliDocsLink { + key: string; + icon: string; + path: string; +} + +export const CLI_DOCS_LINKS: CliDocsLink[] = [ + {key: 'device', icon: 'sensors', path: 'guides/connect-real-device/'}, + {key: 'troubleshooting', icon: 'build', path: 'reference/troubleshooting/'}, + {key: 'all', icon: 'menu_book', path: ''} +]; + +export type CliTermKind = 'you' | 'pick' | 'tool' | 'out' | 'say' | 'ok' | 'ask' | 'done'; + +export interface CliTermRow { + kind: CliTermKind; + text?: string; + tool?: string; + arg?: string; + ms?: number; + options?: string[]; + seconds?: number; +} + +export interface CliTermSession { + tab: string; + banner?: boolean; + intro?: CliTermRow[]; + rows: CliTermRow[]; +} + +export const CLI_VERSION = 'thingsboard-cli 4.4.0.2.post1'; + +export const CLI_ART = [ + ' _____ _ _ ____ _ ', + '|_ _| |__ (_)_ __ __ _ ___| __ ) ___ __ _ _ __ __| |', + ' | | | \'_ \\| | \'_ \\ / _` / __| _ \\ / _ \\ / _` | \'__/ _` |', + ' | | | | | | | | | | (_| \\__ \\ |_) | (_) | (_| | | | (_| |', + ' |_| |_| |_|_|_| |_|\\__, |___/____/ \\___/ \\__,_|_| \\__,_|', + ' |___/ ' +].join('\n'); + +export const CLI_TERM_WAIT: Record = {you: 1200, pick: 300, tool: 380, out: 60, say: 520, ok: 110, ask: 260}; + +export const CLI_TERM_HOLD = 6000; + +export const CLI_TERM_SESSIONS: CliTermSession[] = [ + { + tab: 'office-sensor', + banner: true, + rows: [ + {kind: 'you', text: 'office-sensor.you'}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'office-sensor.written', ms: 2600}, + {kind: 'say', text: 'office-sensor.ready'}, + {kind: 'ok', text: 'office-sensor.device'}, + {kind: 'ok', text: 'office-sensor.alarm'}, + {kind: 'ok', text: 'office-sensor.dashboard'}, + {kind: 'ask', text: 'office-sensor.ask'}, + {kind: 'pick', options: ['office-sensor.stream', 'office-sensor.deploy-only', 'office-sensor.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push office'}, + {kind: 'out', text: 'office-sensor.deployed', ms: 1500}, + {kind: 'tool', tool: 'Bash', arg: 'tb emulator run --duration 5m'}, + {kind: 'out', text: 'office-sensor.streaming', ms: 1100} + ] + }, + { + tab: 'smart-retail', + intro: [ + {kind: 'tool', tool: 'Bash', arg: 'tb device list'}, + {kind: 'out', text: 'smart-retail.devices'}, + {kind: 'say', text: 'smart-retail.connected'}, + {kind: 'done', seconds: 6} + ], + rows: [ + {kind: 'you', text: 'smart-retail.you'}, + {kind: 'tool', tool: 'Skill', arg: 'design-solution-architecture'}, + {kind: 'out', text: 'smart-retail.designed', ms: 2800}, + {kind: 'say', text: 'smart-retail.approve'}, + {kind: 'pick', options: ['smart-retail.step', 'smart-retail.whole']}, + {kind: 'say', text: 'smart-retail.first'}, + {kind: 'ok', text: 'smart-retail.overview'}, + {kind: 'ok', text: 'smart-retail.store'}, + {kind: 'ask', text: 'smart-retail.build'}, + {kind: 'pick', options: ['smart-retail.yes', 'smart-retail.not-yet']}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built', ms: 3000}, + {kind: 'say', text: 'smart-retail.next'} + ] + }, + { + tab: 'freezer-limits', + intro: [ + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built'}, + {kind: 'say', text: 'smart-retail.next'}, + {kind: 'done', seconds: 41} + ], + rows: [ + {kind: 'you', text: 'freezer-limits.you'}, + {kind: 'tool', tool: 'Skill', arg: 'update-solution'}, + {kind: 'out', text: 'freezer-limits.updated', ms: 2400}, + {kind: 'say', text: 'freezer-limits.done'}, + {kind: 'ok', text: 'freezer-limits.attribute'}, + {kind: 'ok', text: 'freezer-limits.alarm'}, + {kind: 'ok', text: 'freezer-limits.dashboard'}, + {kind: 'ask', text: 'freezer-limits.ask'}, + {kind: 'pick', options: ['freezer-limits.push', 'freezer-limits.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push smart-retail --profile dev'}, + {kind: 'out', text: 'freezer-limits.deployed', ms: 1600} + ] + } +]; + +export function cliOs(): CliOs { + const nav = navigator as Navigator & {userAgentData?: {platform?: string}}; + return /win/i.test(nav.userAgentData?.platform || navigator.platform || '') ? 'windows' : 'unix'; +} + +export function asciiGlobe(rows: number, cols: number, cx: number, cy: number, radius: number): string { + const ramp = ' .:-+*'; + const light = [-0.55, -0.62, 0.56]; + const lines: string[] = []; + for (let r = 0; r < rows; r++) { + let line = ''; + for (let c = 0; c < cols; c++) { + const x = (c - cx) * 0.62 / radius; + const y = (r - cy) / radius; + const d = x * x + y * y; + if (d > 1) { + line += (r % 4 === 1 && c % 11 === (r * 3) % 11) ? '.' : ' '; + continue; + } + const z = Math.sqrt(1 - d); + const b = Math.max(0, x * light[0] + y * light[1] + z * light[2]); + const lat = Math.asin(-y); + const lon = Math.atan2(x, z) + 0.35; + const onGrid = Math.abs(Math.sin(lat * 5)) < 0.09 || Math.abs(Math.sin(lon * 6)) < 0.07; + line += onGrid ? ramp[Math.min(ramp.length - 1, 1 + Math.round(b * 4))] : b > 0.82 && (r * 7 + c) % 9 === 0 ? '.' : ' '; + } + lines.push(line); + } + return lines.join('\n'); +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts new file mode 100644 index 0000000000..9dd605d428 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Pipe, PipeTransform } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; + +export interface AiSlotPart { + text?: string; + slot?: string; +} + +export function aiSlotParts(text: string): AiSlotPart[] { + const parts: AiSlotPart[] = []; + const pattern = /\{\{\s*([\w-]+)\s*\}\}/g; + let last = 0; + for (const match of text.matchAll(pattern)) { + if (match.index > last) { + parts.push({text: text.slice(last, match.index)}); + } + parts.push({slot: match[1]}); + last = match.index + match[0].length; + } + if (last < text.length) { + parts.push({text: text.slice(last)}); + } + return parts; +} + +@Pipe({ + name: 'tbAiSlots', + pure: false, + standalone: false +}) +export class AiSlotsPipe implements PipeTransform { + + private translate = inject(TranslateService); + private cacheKey: string; + private cached: AiSlotPart[] = []; + + transform(key: string): AiSlotPart[] { + const text: string = this.translate.instant(key); + const cacheKey = key + '\u0000' + text; + if (cacheKey !== this.cacheKey) { + this.cacheKey = cacheKey; + this.cached = aiSlotParts(text); + } + return this.cached; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.html deleted file mode 100644 index 1d00ac1923..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.html +++ /dev/null @@ -1,47 +0,0 @@ - -
-
solution-creator.alarm-info
-
-
- {{ 'alarm.type' | translate }} - {{ alarm.alarmName }} -
- -
- {{ 'alarm-rule.severities' | translate }} - - @for (key of alarm.severities; track key; let last=$last) { - - {{ key }} - - @if(!last) { - , - } - } - -
- -
- {{ 'solution-creator.entity-profiles' | translate }} - {{ alarm.profileNames.join(', ') }} -
- -
- {{ 'solution-creator.condition' | translate }} - {{ alarm.condition }} -
-
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.ts deleted file mode 100644 index e1e4c2f12a..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/alarm-info-panel.component.ts +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { SolutionDescriptorAlarm } from '@shared/models/solution-creator.models'; -import { alarmSeverityColors } from '@shared/models/alarm.models'; - -@Component({ - selector: 'tb-alarm-info-panel', - templateUrl: './alarm-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class AlarmInfoPanelComponent { - - @Input() - alarm: SolutionDescriptorAlarm; - - protected readonly Object = Object; - - constructor(private popover: TbPopoverComponent) { - } - - cancel() { - this.popover.hide(); - } - - getAlarmSeverityColor(severity: string): string { - const preparedSeverity: any = severity.toUpperCase(); - return alarmSeverityColors.has(preparedSeverity) ? alarmSeverityColors.get(preparedSeverity) : null; - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.html deleted file mode 100644 index 9f6832b319..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.html +++ /dev/null @@ -1,114 +0,0 @@ - -
-
solution-creator.entity-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ entity.name }} -
- -
- {{ 'entity.entity-type' | translate }} - {{ entity.entityType }} -
- - @if (entity.scope) { -
- {{ 'solution-creator.scope' | translate }} - {{ entity.scope }} -
- - } - @if (entity.description) { -
- {{ 'solution-creator.description' | translate }} - {{ entity.description }} -
- - } - @if (entityInfoType) { - - @if (attributes?.length) { - {{ 'attribute.attributes' | translate }} - } - @if (timeseries?.length) { - {{ 'attribute.scope-telemetry' | translate }} - } - @if (relations?.length) { - {{ 'relation.relations' | translate }} - } - - @switch (entityInfoType) { - @case ('ATTRIBUTE') { - @for (key of attributes ; track key.key; let last=$last) { -
- {{ key.key }} - {{ key.dataType | titlecase }} - @if (key.enumValues) { - ({{ key.enumValues.join('/') }}) - } - -
- @if (!last) { - - } - } - } - @case ('TIMESERIES') { - @for (key of timeseries; track key.key; let last=$last) { -
- {{ key.key}} - @if (key.calculatedFieldName) { - - mdi:function-variant - - } @else if (key.units) { -  ({{ key.units }}) - } - - {{ key.dataType | titlecase }} - @if (key.enumValues) { - ({{ key.enumValues.join('/') }}) - } - -
- @if (!last) { - - } - } - } - @case ('RELATION') { - @for (relation of relations; track relation.child; let last = $last) { -
- {{ relation.child }} - {{ relation.type }} - @if (relation.cardinality) { - ({{ relation.cardinality }}) - } - -
- @if (!last) { - - } - } - } - } - } -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.scss deleted file mode 100644 index fec548ccf3..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.scss +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@import '../scss/constants'; - -.tb-entity-info-panel { - width: 400px; - display: flex; - flex-direction: column; - gap: 16px; - height: 100%; - max-height: calc(100vh - 24px); - @media #{$mat-xs} { - width: 80vw; - } - .tb-entity-info-title { - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.87); - } - .tb-entity-info-panel-content { - display: flex; - flex-direction: column; - overflow: auto; - margin: -8px; - padding: 8px; - --mat-divider-color: rgba(0, 0, 0, 0.1); - - .property { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.25px; - margin: 12px 0; - display: flex; - justify-content: space-between; - gap: 16px; - - span:first-child { - font-weight: 500; - white-space: nowrap; - min-width: 120px; - tb-icon { - vertical-align: text-bottom; - color: rgba(0, 0, 0, 0.54); - } - span { - font-weight: 400; - color: rgba(0, 0, 0, 0.54); - } - } - - span:last-child { - span { - font-style: italic; - color: rgba(0, 0, 0, 0.54); - } - } - - &.column { - flex-direction: column; - gap: 8px; - - .condition-text { - padding: 8px 12px; - background: rgba(0, 0, 0, 0.04); - border-radius: 6px; - font-size: 13px; - line-height: 18px; - color: rgba(0, 0, 0, 0.76); - white-space: pre-wrap; - word-break: break-word; - } - - .description-text { - font-size: 13px; - line-height: 18px; - color: rgba(0, 0, 0, 0.54); - white-space: pre-wrap; - word-break: break-word; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.ts deleted file mode 100644 index 8e27cd86f3..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/entity-info-panel.component.ts +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { - SolutionDescriptorEntityBaseRelation, - SolutionDescriptorEntityBaseTelemetry, - SolutionEntity -} from '@shared/models/solution-creator.models'; - -@Component({ - selector: 'tb-entity-info-panel', - templateUrl: './entity-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class EntityInfoPanelComponent implements OnInit { - - @Input() - entity: SolutionEntity; - - @Input() - relations: SolutionDescriptorEntityBaseRelation[] = []; - - entityInfoType: 'ATTRIBUTE' | 'TIMESERIES' | 'RELATION'; - - attributes: SolutionDescriptorEntityBaseTelemetry[]; - timeseries: SolutionDescriptorEntityBaseTelemetry[]; - - constructor(private popover: TbPopoverComponent) { - } - - ngOnInit() { - this.attributes = this.entity.telemetry?.filter((item) => item.telemetryType === 'ATTRIBUTE'); - this.timeseries = this.entity.telemetry?.filter((item) => item.telemetryType === 'TIMESERIES'); - if (this.attributes?.length) { - this.entityInfoType = 'ATTRIBUTE'; - } else if (this.timeseries?.length) { - this.entityInfoType = 'TIMESERIES'; - } else if (this.relations?.length) { - this.entityInfoType = 'RELATION'; - } - } - - cancel() { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.html deleted file mode 100644 index bebe45896c..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.html +++ /dev/null @@ -1,34 +0,0 @@ - -
-
solution-creator.iam-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ iam.name }} -
- -
- {{ 'permission.operation.operations' | translate }} - {{ operations }} -
- -
- {{ 'solution-creator.description' | translate }} - {{ iam.description }} -
- -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.ts deleted file mode 100644 index 486615bdf9..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/iam-info-panel.component.ts +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { SolutionDescriptorIam } from '@shared/models/solution-creator.models'; -import { TranslateService } from '@ngx-translate/core'; - -@Component({ - selector: 'tb-iam-info-panel', - templateUrl: './iam-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class IamInfoPanelComponent implements OnInit { - - @Input() - iam: SolutionDescriptorIam; - - operations: string; - - constructor(private popover: TbPopoverComponent, - private translate: TranslateService) { - } - - ngOnInit() { - this.operations = this.iam.permissions.split('') - .map(operation => this.translate.instant(`solution-creator.operation.${operation}`)) - .join(', '); - } - - cancel() { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.html deleted file mode 100644 index 4981cadea4..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.html +++ /dev/null @@ -1,41 +0,0 @@ - -
-
solution-creator.calculated-field-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ metric.calculatedFieldName }} -
- -
- {{ 'solution-creator.entity-profile' | translate }} - {{ metric.profileName }} -
- -
- {{ 'solution-creator.field-type' | translate }} - {{ getMetricTypeName(metric.metricType) }} -
- - @if (metric.calculation) { -
- {{ 'solution-creator.description' | translate }} - {{ metric.calculation }} -
- - } -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.ts deleted file mode 100644 index 4312bdb8cd..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/metric-info-panel.component.ts +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { AiMetricType, SolutionDescriptorMetric } from '@shared/models/solution-creator.models'; -import { CalculatedFieldTypeTranslations } from '@shared/models/calculated-field.models'; -import { TranslateService } from '@ngx-translate/core'; - -@Component({ - selector: 'tb-metric-info-panel', - templateUrl: './metric-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class MetricInfoPanelComponent { - - @Input() - metric: SolutionDescriptorMetric; - - constructor(private popover: TbPopoverComponent, - private translate: TranslateService) { - } - - cancel() { - this.popover.hide(); - } - - getMetricTypeName(value: keyof AiMetricType): string { - if (AiMetricType[value]) { - return this.translate.instant(CalculatedFieldTypeTranslations.get(AiMetricType[value]).name); - } - return value as any; - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.html deleted file mode 100644 index 690c992ffc..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.html +++ /dev/null @@ -1,52 +0,0 @@ - -
- -
{{ 'solution-creator.dashboards-overview' | translate: {name: solutionName} }}
- - {{ 'solution-creator.basic-mode' | translate }} - {{ 'solution-creator.advanced-mode' | translate }} - -
-
- @if (solutionMode.value === 'basic') { -
-
- - @for (dashboard of dashboards; track dashboard.name) { - - {{ dashboard.name }} - {{ dashboard.assignedTo }} - - } - -
-
- -
-
- } - @else { - -
- -
- } -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.ts deleted file mode 100644 index 61ecceb8e1..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component.ts +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { AfterContentInit, Component, EventEmitter, HostBinding, Input, OnChanges, Output } from "@angular/core"; -import { DashboardsOverview } from '@shared/models/solution-creator.models'; -import { FormBuilder } from '@angular/forms'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { deepClone } from '@core/utils'; - -@Component({ - selector: 'tb-solution-creator-overview-dashboard', - templateUrl: './solution-creator-overview-dashboard.component.html', - styleUrls: ['./solution-creator-overview.scss'], - standalone: false -}) -export class SolutionCreatorOverviewDashboardComponent implements OnChanges, AfterContentInit { - - @Input({required: true}) - dashboards: DashboardsOverview[]; - - @Input({required: true}) - solutionName: string; - - @Output() - updatedDashboards: EventEmitter = new EventEmitter(); - - @HostBinding('class.entering') - initComponent = false; - - dashboard = this.fb.control([''], {nonNullable: true}); - dashboardDescriptor = this.fb.control(null); - solutionMode = this.fb.control('basic'); - description: string; - - constructor(private fb: FormBuilder, - ) { - this.dashboard.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - const dashboard = this.dashboards.find(item => item.name === value[0]); - this.description = dashboard?.description ?? 'Not found'; - }) - - this.solutionMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'advanced') { - this.dashboardDescriptor.setValue(deepClone(this.dashboards)); - this.dashboardDescriptor.markAsPristine(); - } - }) - } - - ngOnChanges(): void { - if (this.dashboards.length) { - if (!this.dashboards.find(item => item.name === this.dashboard.value[0])) { - this.dashboard.setValue([this.dashboards[0]?.name]); - } - if (this.dashboardDescriptor.pristine) { - this.dashboardDescriptor.setValue(deepClone(this.dashboards)); - } - } - } - - ngAfterContentInit() { - requestAnimationFrame(() => { - this.initComponent = true; - }) - } - - updatedDashboardsDescriptor($event: MouseEvent) { - $event?.stopPropagation(); - this.dashboardDescriptor.markAsPristine(); - this.updatedDashboards.emit(this.dashboardDescriptor.value); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.html deleted file mode 100644 index 49ad679de6..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.html +++ /dev/null @@ -1,315 +0,0 @@ - -
- -
{{ 'solution-creator.solution-overview' | translate: {name: solutionName} }}
- - {{ 'solution-creator.basic-mode' | translate }} - {{ 'solution-creator.advanced-mode' | translate }} - -
-
- @if (solutionMode.value === 'basic') { -
-
- - @for (entity of solutionEntities; track entity) { - @if (entity.value === 'entityProfiles' || description[entity.value]?.length) { - {{ entity.title | translate }} - } - } - -
-
-
-
{{ solutionEntityTitle | translate }}
- - {{ 'solution-creator.table-view' | translate }} - {{ 'solution-creator.schema-view' | translate }} - -
- @if (profileMode.value === 'table' || solutionEntity.value[0] !== 'entityProfiles') { -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{{ 'solution-creator.name' | translate }} {{element.name}} {{ 'solution-creator.name' | translate }} {{element.calculatedFieldName}} {{ 'entity.entity-type' | translate }} {{element.entityType}} {{ 'solution-creator.data' | translate }} - @if (element.telemetry?.length || getEntityRelations(element.name).length) { -
- @for (keyInfo of element.telemetry; track keyInfo.key) { - - } - @for (relation of getEntityRelations(element.name); track relation.child) { - - } -
- } -
{{ 'solution-creator.entity-profile' | translate }} - - {{ 'alarm.type' | translate }}{{ element.alarmName }}{{ 'solution-creator.entity-profiles' | translate}} -
- @if (element.entityProfiles?.length) { -
- @for (entityProfile of element.entityProfiles; track entityProfile) { - - } -
- } -
-
{{ 'solution-creator.entity-profiles' | translate}} -
- @if (element.profileNames?.length) { -
- @for (entityProfile of element.profileNames; track entityProfile) { - - } -
- } -
-
{{ 'alarm-rule.severities' | translate }} - @for (key of element.severities; track key; let last=$last) { - - {{ key }} - - @if(!last) { - , - } - } - {{ 'permission.operation.operations' | translate }} -
- @for (operation of element.permissions.split(''); track operation) { - - } -
-
- - - - - - - - - -
-
- } @else { -
- - - - - - - - - - - - {{ cluster.label }} - - - - - - -
-
-
{{ node.label }}
-
{{ node.data?.entityType }}
-
-
- info_outline -
-
-
-
- - - - - - -
{{ link.label }}
-
-
-
-
-
-
- } -
-
- } - @else { - -
- -
- } -
-
- -
- {{ title }} -
-
- -
- @switch (type) { - @case ('TIMESERIES') { - timeline - } - @case ('ATTRIBUTE') { - mdi:alpha-a-circle-outline - } - @case ('relation') { - mdi:repeat - } - } - {{ title }} -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.scss deleted file mode 100644 index b622dacb73..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.scss +++ /dev/null @@ -1,120 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - .tb-solution-settings { - .tb-solution-settings-table-toolbar { - height: 48px; - padding: 0 12px; - display: flex; - align-items: center; - font-size: 16px; - line-height: 24px; - font-weight: 500; - } - - .tb-solution-settings-container { - &::ng-deep { - .mat-mdc-table { - .mat-mdc-header-row { - height: 48px; - - th { - font-size: 14px; - } - } - .mat-mdc-row { - height: 48px; - } - } - - .tb-primary-fill:before { - opacity: 0.1; - } - } - } - - .graph-container { - .node { - padding: 8px 12px; - border-radius: 8px; - border: 1px solid; - background: #fff; - min-width: 180px; - text-align: left; - min-height: 54px; - &.customer { - border-color: #2B90D9; - border-left-width: 4px; - } - - &.asset { - border-color: #8C46C8; - border-left-width: 4px; - } - - &.device { - border-color: #EC8B29; - border-left-width: 4px; - } - - &.user { - border-color: #40985C; - border-left-width: 4px; - } - .title { - font-weight: 500; - font-size: 14px; - line-height: 18px; - } - - .subtitle { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.76); - } - - .node-info-btn { - display: flex; - align-items: flex-start; - cursor: pointer; - color: #B1B1B1; - - &:hover { - color: rgba(0, 0, 0, 0.54); - } - } - } - .edge-label-text { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.76); - text-align: center; - background: #fff; - border: 1px solid rgba(0,0,0,0.08); - padding: 2px 6px; - border-radius: 4px; - white-space: nowrap; - max-width: fit-content; - margin: 0 auto; - } - - .cluster { - border: 2px dashed rgba(0,0,0,0.15); - border-radius: 14px; - background: rgba(0,0,0,0.02); - padding: 8px; - - .cluster-title { - font-size: 14px; - fill: rgba(0, 0, 0, 0.54); - } - } - } - } - - ::ng-deep { - .tb-chip, .tb-overflow-chip { - padding: 4px 8px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.ts deleted file mode 100644 index 203ff1dd1d..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component.ts +++ /dev/null @@ -1,427 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { - AfterContentInit, - Component, - ElementRef, - EventEmitter, - HostBinding, - Input, - OnChanges, - OnDestroy, - Output, - Renderer2, - Type, - ViewChild, - ViewContainerRef -} from "@angular/core"; -import { - SolutionDescriptor, - SolutionDescriptorAlarm, - SolutionDescriptorEntityBase, - SolutionDescriptorEntityBaseRelation, - SolutionDescriptorIam, - SolutionDescriptorMetric, - SolutionEntity -} from '@shared/models/solution-creator.models'; -import { FormBuilder } from '@angular/forms'; -import { TbTableDatasource } from '@shared/components/table/table-datasource.abstract'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { deepClone } from '@core/utils'; -import { alarmSeverityColors } from '@shared/models/alarm.models'; -import { TbPopoverService } from '@shared/components/popover.service'; -import { MatIconButton } from '@angular/material/button'; -import { AlarmInfoPanelComponent } from './alarm-info-panel.component'; -import { EntityInfoPanelComponent } from './entity-info-panel.component'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { ClusterNode, Edge, GraphComponent, Node } from '@swimlane/ngx-graph'; -import { MetricInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/metric-info-panel.component'; -import { IamInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/iam-info-panel.component'; -import { StrictPopoverPlacements } from '@shared/components/popover.models'; - -@Component({ - selector: 'tb-solution-creator-overview-entities', - templateUrl: './solution-creator-overview-entities.component.html', - styleUrls: ['./solution-creator-overview.scss', './solution-creator-overview-entities.component.scss'], - standalone: false -}) -export class SolutionCreatorOverviewEntitiesComponent implements OnChanges, AfterContentInit, OnDestroy { - - @Input({required: true}) - description: SolutionDescriptor; - - @Input({required: true}) - solutionName: string; - - @Output() - updatedDescription: EventEmitter = new EventEmitter(); - - @HostBinding('class.entering') - initComponent = false; - - readonly solutionEntities = [ - {value: 'entityProfiles', title: 'solution-creator.entity-profiles'}, - {value: 'iam', title: 'solution-creator.iam', fullTitle: 'solution-creator.iam-full'}, - {value: 'metrics', title: 'entity.type-calculated-fields'}, - {value: 'alarms', title: 'alarm.alarms'}, - ]; - - protected readonly Object = Object; - - solutionEntity = this.fb.control(['entityProfiles'], {nonNullable: true}); - solutionEntityTitle = 'solution-creator.entity-profiles'; - solutionDescriptor = this.fb.control(null); - solutionMode = this.fb.control('basic'); - profileMode = this.fb.control('table'); - nodes: Node[] = []; - links: Edge[] = []; - clusters: ClusterNode[] = []; - @ViewChild('graphContainer', {static: false}) graphContainer: ElementRef; - @ViewChild(GraphComponent) graphComponent: GraphComponent; - private graphResizeObserver: ResizeObserver; - - displayedColumns: string[] = ['name', 'entityType', 'data', 'entityActions']; - dataSource = new EntityOverviewDatasource(); - - constructor(private fb: FormBuilder, - private popoverService: TbPopoverService, - private renderer: Renderer2, - private viewContainerRef: ViewContainerRef, - private dialog: DialogService, - private translate: TranslateService, - ) { - this.solutionEntity.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (this.profileMode.value !== 'table') { - this.profileMode.setValue('table'); - } else { - this.prepareEntityToDatasource(value[0]); - } - }) - - this.solutionMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'basic') { - this.dataSource = new EntityOverviewDatasource(); - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - } else { - this.solutionDescriptor.setValue(deepClone(this.description)); - this.solutionDescriptor.markAsPristine(); - } - }) - - this.profileMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'table') { - this.dataSource = new EntityOverviewDatasource(); - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - } else { - this.prepareSchemaData(); - requestAnimationFrame(() => this.observeGraphResize()); - } - }) - } - - ngOnChanges(): void { - if (this.description) { - if (this.description && this.solutionEntity.value[0] !== 'entityProfiles' - && !this.description[this.solutionEntity.value[0]].length) { - this.solutionEntity.setValue(['entityProfiles'], {emitEvent: false}); - } - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - if (this.solutionDescriptor.pristine) { - this.solutionDescriptor.setValue(deepClone(this.description)); - } - if (this.profileMode.value !== 'table') { - this.prepareSchemaData(); - } - } - } - - ngAfterContentInit() { - requestAnimationFrame(() => { - this.initComponent = true; - }) - } - - ngOnDestroy(): void { - this.graphResizeObserver?.disconnect(); - } - - observeGraphResize(): void { - this.graphResizeObserver?.disconnect(); - if (this.graphContainer?.nativeElement) { - this.graphResizeObserver = new ResizeObserver(() => { - this.graphComponent?.basicUpdate(); - }); - this.graphResizeObserver.observe(this.graphContainer.nativeElement); - } - } - - getAlarmSeverityColor(severity: string): string { - const preparedSeverity: any = severity.toUpperCase(); - return alarmSeverityColors.has(preparedSeverity) ? alarmSeverityColors.get(preparedSeverity) : null; - } - - getEntityRelations(entityName: string): SolutionDescriptorEntityBaseRelation[] { - return this.description?.relations?.filter(r => r.parent === entityName) ?? []; - } - - openAlarmInfo(event: Event, matButton: MatIconButton, alarm: SolutionDescriptorAlarm): void { - this.openInfoPopover(event, matButton, AlarmInfoPanelComponent, true, { alarm }); - } - - openEntityInfo(event: Event, ref: MatIconButton | HTMLElement, entity: SolutionEntity, fixedPosition = true): void { - const relations = this.getEntityRelations(entity.name); - this.openInfoPopover(event, ref, EntityInfoPanelComponent, fixedPosition, { entity, relations }); - } - - openMetricInfo(event: Event, matButton: MatIconButton, metric: SolutionDescriptorMetric): void { - this.openInfoPopover(event, matButton, MetricInfoPanelComponent, true, { metric }); - } - - openIamInfo(event: Event, matButton: MatIconButton, iam: SolutionDescriptorIam): void { - this.openInfoPopover(event, matButton, IamInfoPanelComponent, true, { iam }); - } - - deleteAlarm($event: Event, alarm: SolutionDescriptorAlarm): void { - $event?.stopPropagation(); - 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((value) => { - if (value) { - const updated = { ...this.description, alarms: this.description.alarms.filter(item => item !== alarm) }; - this.updatedDescription.emit(updated); - } - }); - } - - updatedSolutionDescriptor($event: MouseEvent) { - $event?.stopPropagation(); - this.solutionDescriptor.markAsPristine(); - this.updatedDescription.emit(this.solutionDescriptor.value); - } - - private openInfoPopover(event: Event, ref: MatIconButton | HTMLElement, componentType: Type, fixedPosition: boolean, - context: Record): void { - event?.stopPropagation(); - const trigger = ref instanceof HTMLElement ? ref : ref._elementRef.nativeElement; - if (this.popoverService.hasPopover(trigger)) { - this.popoverService.hidePopover(trigger); - } else { - this.popoverService.displayPopover({ - trigger, - renderer: this.renderer, - componentType, - hostView: this.viewContainerRef, - preferredPlacement: fixedPosition - ? ['leftTopOnly', 'leftOnly', 'leftBottomOnly'] - : StrictPopoverPlacements as any, - context, - showCloseButton: true, - overlayStyle: {maxHeight: '80vh', height: '100%'} - }); - } - } - - private prepareEntityToDatasource(type: string) { - const findEntity = this.solutionEntities.find(entity => entity.value === type); - this.solutionEntityTitle = findEntity?.fullTitle ?? findEntity?.title ?? ''; - switch (type) { - case 'entityProfiles': - this.displayedColumns = ['name', 'entityType', 'telemetry', 'entityActions']; - this.dataSource.loadData(this.prepareEntityProfiles()); - break; - case 'metrics': - this.displayedColumns = ['calculatedFieldName', 'profileName', 'metricActions']; - this.dataSource.loadData(this.description.metrics); - break; - case 'alarms': - this.displayedColumns = ['alarmName', 'profileNames', 'severities', 'alarmActions']; - this.dataSource.loadData(this.description.alarms); - break; - case 'iam': - this.displayedColumns = ['name', 'permissions', 'iamActions']; - this.dataSource.loadData(this.description.iam); - break; - default: - this.dataSource.loadData([]); - } - } - - private prepareEntityProfiles(): SolutionDescriptorEntityBase[] { - const data: SolutionDescriptorEntityBase[] = []; - Object.values(this.description.entityProfiles).forEach((entities: SolutionEntity[]) => { - entities.forEach((entity: SolutionEntity) => { - data.push(entity); - }) - }); - return data; - } - - private prepareSchemaData() { - this.links = []; - this.nodes = []; - this.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 = { id, label: scope, childNodeIds: [] }; - clusterByScope.set(scope, clusterNode); - this.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); - } - - this.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; - this.links.push({ id, source: sourceId, target: targetId, label: lbl || undefined }); - linkIdSet.add(id); - }; - - const allProfiles: SolutionDescriptorEntityBase[] = Object.values(this.prepareEntityProfiles()).flat(); - - for (const entity of allProfiles) { - addNode(entity); - } - - for (const relation of this.description.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'); - - // Tenant -> Customer (manages), if both exist - for (const t of tenantUsers) { - const tId = nodeByName.get(t.name)?.id; - if (!tId) continue; - for (const c of customers) { - if (!this.description.relations.some(x => x.child === c.name)) { - const cId = nodeByName.get(c.name)?.id; - if (cId) pushLink(tId, cId, 'Manages'); - } - } - } - - // Customer -> Asset (owns) when scope aligns - 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 (!this.description.relations.some(x => x.child === a.name)) { - const aId = nodeByName.get(a.name)?.id; - if (aId) pushLink(cId, aId, 'Own'); - } - } - } - } - - // Customer -> Device (owns) when scope aligns - 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 (!this.description.relations.some(x => x.child === d.name)) { - const aId = nodeByName.get(d.name)?.id; - if (aId) pushLink(cId, aId, 'Own'); - } - } - } - } - - // Customer -> User (role) when scope aligns - 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 (!this.description.relations.some(x => x.child === u.name)) { - const uId = nodeByName.get(u.name)?.id; - if (uId) pushLink(cId, uId, 'Manages'); - } - } - } - } - } -} - - -class EntityOverviewDatasource extends TbTableDatasource { -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview.scss deleted file mode 100644 index 8650103bda..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/overview/solution-creator-overview.scss +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - .tb-solution-settings { - z-index: 2; - display: flex; - flex: 1; - flex-direction: column; - min-width: 0; - min-height: 0; - overflow: hidden; - border-left: 1px solid rgba(0, 0, 0, 0.12); - - .tb-solution-settings-toolbar { - height: 50px; - min-height: 50px; - padding: 0 12px; - justify-content: space-between; - --mat-toolbar-container-background-color: #fff; - --mat-toolbar-title-text-size: 18px; - border-bottom: 1px solid rgba(0, 0, 0, 0.12); - } - - .tb-solution-settings-container { - padding: 12px; - display: flex; - flex-direction: column; - overflow: hidden; - flex: 1; - gap: 16px; - - .tb-solution-settings-container-setting { - display: flex; - flex: 1; - min-height: 0; - border-radius: 8px; - border: 1px solid rgba(0, 0, 0, 0.12); - overflow: hidden; - - .tb-solution-menu-container { - overflow: auto; - border-right: 1px solid rgba(0, 0, 0, 0.12); - } - - .tb-solution-menu { - padding: 0; - --mat-list-list-item-label-text-weight: 500; - .mdc-list-item { - border-bottom: 1px solid rgba(0, 0, 0, 0.12); - } - .mdc-list-item--selected { - border-bottom-color: var(--tb-primary-500); - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; - } - } - } - } - - &::ng-deep { - tb-json-object-edit .tb-json-object-panel { - margin-left: 0; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html deleted file mode 100644 index 0ca38ceb57..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html +++ /dev/null @@ -1,78 +0,0 @@ - - diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss deleted file mode 100644 index cac17e2ad8..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss +++ /dev/null @@ -1,133 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - border-radius: 8px; - .side-bar { - border-radius: 8px; - border: 1px solid rgba(0, 0, 0, 0.12); - width: 56px; - height: 100%; - padding: 12px 8px; - display: flex; - flex-direction: column; - - &.with-transition { - transition: width 0.15s ease-in-out; - } - - &.expanded { - width: 240px; - } - &:not(.expanded) { - cursor: pointer; - } - } - .list-chats { - overflow: auto; - --mat-button-text-label-text-weight: 400; - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.87); - .title { - padding: 0 8px; - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.38); - margin-bottom: 8px; - } - a { - letter-spacing: 0.25px; - border-radius: 4px; - } - - } - .icon-button { - font-size: 0; - display: inline-flex; - } -} - -:host ::ng-deep { - .mat-mdc-button.mat-mdc-button-base { - display: inline-flex; - width: 100%; - height: 40px; - min-height: 40px; - align-items: center; - overflow: hidden; - line-height: 32px; - border-radius: 0; - .actions:not(:hover) { - --mat-button-text-hover-state-layer-opacity: 0; - } - .actions:not(.open-menu) { - display: none; - } - &:hover { - background-color: rgba(255,255,255,0.08); - padding-right: 0; - .actions { - display: block; - } - } - &.tb-active { - --mat-button-text-hover-state-layer-opacity: 0; - - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; - } - } - .mat-icon { - margin-right: 8px; - } - &.menu { - &.open-menu { - padding-right: 0; - .mat-mdc-button-persistent-ripple::before { - opacity: var(--mat-button-text-hover-state-layer-opacity, var(--mat-app-hover-state-layer-opacity)); - content: ""; - } - } - .mat-icon { - margin: auto; - } - } - span.mdc-button__label { - width: 100%; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - display: inline-flex; - align-items: center; - & > span { - flex: 1; - overflow: hidden; - text-overflow: ellipsis; - } - } - } -} -::ng-deep { - .solution-menu.mat-mdc-menu-panel { - --mat-menu-item-spacing: 8px; - --mat-menu-item-label-text-size: 14px; - --mat-menu-item-with-icon-leading-spacing: 12px; - --mat-menu-item-with-icon-trailing-spacing: 12px; - - .mat-mdc-menu-item { - min-height: 40px; - } - - .delete { - --mat-menu-item-icon-color: var(--tb-accent-500); - --mat-menu-item-label-text-color: var(--tb-accent-500); - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts deleted file mode 100644 index 6051b13301..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts +++ /dev/null @@ -1,179 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, EventEmitter, OnInit, Output, signal } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; -import { SolutionCreatorInfo, SolutionInfo } from '@shared/models/solution-creator.models'; -import { ActivatedRoute, Router } from '@angular/router'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; -import { AppState } from '@core/core.state'; -import { select, Store } from '@ngrx/store'; -import { selectUserSettingsProperty } from '@core/auth/auth.selectors'; -import { distinctUntilChanged, skip, take } from 'rxjs/operators'; -import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; -import { ActionPreferencesPutUserSettings } from '@core/auth/auth.actions'; -import { HttpErrorResponse } from '@angular/common/http'; -import { DomSanitizer } from '@angular/platform-browser'; -import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; - -@Component({ - selector: 'tb-solution-side-bar', - templateUrl: './solution-side-bar.component.html', - styleUrls: ['./solution-side-bar.component.scss'], - standalone: false -}) -export class SolutionSideBarComponent extends PageComponent implements OnInit { - - isExpanded = signal(false); - solutions = signal>([]); - - enableTransition = false; - - @Output() - updatedSolution = new EventEmitter(); - - @Output() - installedChanged = new EventEmitter<{solutionId: string, installed: boolean}>(); - - constructor( - private solutionCreator: SolutionsCreatorService, - private dialog: DialogService, - private translate: TranslateService, - private router: Router, - private route: ActivatedRoute, - protected store: Store, - private sanitizer: DomSanitizer, - ) { - super(); - this.store.pipe(select(selectUserSettingsProperty('isSolutionSidebarExpanded'))).pipe( - take(1) - ).subscribe((settings: boolean) => { - if (settings) { - this.isExpanded.set(settings); - } - }) - - toObservable(this.isExpanded).pipe( - takeUntilDestroyed(), - skip(1), - distinctUntilChanged() - ).subscribe(value => { - this.store.dispatch(new ActionPreferencesPutUserSettings({isSolutionSidebarExpanded: value })); - }); - } - - ngOnInit() { - this.solutionCreator.getSolutions({ignoreLoading: true, ignoreErrors: true}).subscribe({ - next: solutions => this.solutions.set(solutions), - error: error => this.showError(error) - }); - } - - toggleSidebar($event: Event): void { - $event?.stopPropagation(); - this.enableTransition = true; - this.isExpanded.set(!this.isExpanded()); - } - - expandSidebar(): void { - if (!this.isExpanded()) { - this.enableTransition = true; - this.isExpanded.set(true); - } - } - - deleteSolution(solution: SolutionInfo): void { - this.dialog.confirm( - this.translate.instant('solution-creator.delete-solution-title', { - name: solution.solutionTitle || this.translate.instant('solution-creator.new-solution') - }), - this.translate.instant('solution-creator.delete-solution-text'), - this.translate.instant('action.no'), - this.translate.instant('solution-creator.delete-solution-confirm') - ).subscribe((value) => { - if (value) { - this.solutionCreator.deleteSolution(solution.id, {ignoreErrors: true}).subscribe({ - next: () => { - this.solutions.update(solutions => solutions.filter(s => s.id !== solution.id)); - if (this.route.snapshot.queryParamMap.has('solutionId') && this.route.snapshot.queryParamMap.get('solutionId') === solution.id) { - this.router.navigate(['/ai-solution-creator']).then(() => {}); - } - }, - error: error => this.showError(error) - }); - } - }) - } - - addNewSolutionTemplate(solution: SolutionInfo): void { - const findSolutionIndex = this.solutions().findIndex(s => s.id === solution.id); - if (findSolutionIndex !== -1) { - this.updateSolutionField(solution, solution); - } else { - this.solutions.update(solutions => [solution, ...solutions]); - } - } - - renameSolution(solution: SolutionInfo): void { - this.dialog.dialog.open(AiRenameDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - title: this.translate.instant('solution-creator.rename-solution-title'), - value: solution.solutionTitle || this.translate.instant('solution-creator.new-solution') - } - }).afterClosed().subscribe(newTitle => { - if (newTitle && newTitle !== solution.solutionTitle) { - this.solutionCreator.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(newTitle), {ignoreErrors: true}) - .subscribe({ - next: value => { - solution.solutionTitle = newTitle; - this.updatedSolution.next(value); - }, - error: error => this.showError(error) - }); - } - }); - } - - uninstallSolution(solution: SolutionInfo): void { - this.dialog.confirm( - this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: solution.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(solution.id, {ignoreErrors: true}).subscribe({ - next: () => { - this.updateSolutionField(solution, {installed: false}); - this.installedChanged.emit({solutionId: solution.id, installed: false}); - }, - error: error => this.showError(error) - }); - } - }); - } - - private showError(error: unknown): void { - const responseType = isNotEmptyStr((error as {error?: unknown})?.error) ? 'text' : undefined; - this.store.dispatch(new ActionNotificationShow({ - message: parseHttpErrorMessage(error as HttpErrorResponse, this.translate, responseType, this.sanitizer).message, - modern: true, - type: 'error', - target: 'solution-creator', - verticalPosition: 'top', - horizontalPosition: 'center' - })); - } - - updateSolutionField(solution: SolutionInfo | {id: string}, fields: Partial): void { - const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); - this.solutions.update(solutions => - solutions.map(s => s.id === solution.id ? {...s, ...defined} : s) - ); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts deleted file mode 100644 index 1a73f11d6b..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { Authority } from '@shared/models/authority.enum'; -import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; -import { MenuId } from '@core/services/menu.models'; -import { SolutionCreatorComponent } from '@home/pages/ai-solution-creator/solution-creator.component'; - -const routes: Routes = [ - { - path: 'ai-solution-creator', - component: SolutionCreatorComponent, - data: { - breadcrumb: { - menuId: MenuId.ai_solution_creator - }, - auth: [Authority.TENANT_ADMIN], - canActivate: (userPermissionsService: UserPermissionsService): boolean => { - return userPermissionsService.isAiEnabled() && userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); - }, - } - } -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], - providers: [] -}) -export class SolutionCreatorRoutingModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html deleted file mode 100644 index 9c901722c2..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html +++ /dev/null @@ -1,230 +0,0 @@ - -
- - -
-
- @for (step of stepperLabels; track step; let i = $index) { - @let status = stepStatuses()[i]; -
-
- @if (status === 'ready') { - check - } @else { - {{ i + 1 }} - } -
- {{ step | translate }} -
- @if (i < stepperLabels.length - 1) { -
- } - } -
- @switch (creatorStep()) { - @case ('chat') { -
-
- @if (isInitialEmpty()) { -
- - - -
-
solution-creator.main-title
-
solution-creator.sub-title
-
-
- } - @if (messages().length || (loading() && !isGenerating())) { -
-
- -
- Loading -
- solution-creator.analyzing-your-request -
-
-
-
- } -
- - - @if (isInitialEmpty()) { -
- @for (ex of solutionExamples; track ex.key) { - - } -
- @if (solutionExamples.length > 3) { - - } - } @else { -
- @if (solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - - } - - @if (skipInterviewAllowed()) { - - } - @if (solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - - } - @if (solutionStep() !== SolutionStep.INITIAL_CONFIGURATION || messages().length) { - - } -
- } -
-
- @if (isReadyStep()) { - @switch (solutionStep()) { - @case(SolutionStep.INITIAL_CONFIGURATION) { - - - } - @case(SolutionStep.DASHBOARDS_CONFIGURATION) { - - - } - } - } -
- } - @case ('result') { -
- - - -
-
- {{(solutionMetadata.installed ? 'solution-creator.success-generate-install-title' : 'solution-creator.success-generate-title') | translate }} -
-
- {{(solutionMetadata.installed ? 'solution-creator.success-generate-install-sub-title' : 'solution-creator.success-generate-sub-title') | translate }} -
-
-
-
- - @if (solutionMetadata.installResult?.mainDashboardId) { - - } - -
-
- @if (solutionMetadata.installed) { - - } @else { - - } -
-
-
- } - @default { -
-
- } - } -
-
diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.scss deleted file mode 100644 index 04ed56742c..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.scss +++ /dev/null @@ -1,295 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - width: 100%; - height: 100%; - display: flex; - padding: 8px; - overflow: hidden; - - .image-main-color { - color: var(--tb-primary-500); - } - - .solution-creator { - & > * { - background-color: #fff; - } - - .solution-content { - border: 1px solid rgba(0, 0, 0, .12); - } - - .solution-stepper-header { - display: flex; - align-items: center; - padding: 12px 24px; - flex-shrink: 0; - border-bottom: 1px solid rgba(0, 0, 0, .12); - max-height: 56px; - opacity: 1; - overflow: hidden; - transition: max-height 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - padding 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - border-bottom-width 400ms cubic-bezier(0.25, 0.8, 0.25, 1); - - &.collapsed { - max-height: 0; - opacity: 0; - padding-top: 0; - padding-bottom: 0; - border-bottom-width: 0; - } - - .stepper-step { - display: flex; - align-items: center; - gap: 8px; - - .stepper-icon { - width: 24px; - height: 24px; - border-radius: 50%; - display: flex; - align-items: center; - justify-content: center; - font-size: 12px; - font-weight: 500; - flex-shrink: 0; - background-color: rgba(0, 0, 0, .12); - color: rgba(0, 0, 0, .54); - transition: background-color 300ms ease, color 300ms ease; - } - - .stepper-label { - font-size: 14px; - color: rgba(0, 0, 0, .54); - white-space: nowrap; - transition: color 300ms ease, text-shadow 300ms ease; - } - - &.active, - &.ready { - .stepper-icon { - background-color: var(--tb-primary-500); - color: #fff; - } - - .stepper-label { - color: rgba(0, 0, 0, .87); - } - } - - &.active .stepper-label { - text-shadow: 0 0 .65px currentColor, 0 0 .65px currentColor; - } - - &.ready { - cursor: pointer; - - &:hover { - .stepper-icon { - background-color: var(--tb-primary-700); - } - - .stepper-label { - color: var(--tb-primary-700); - } - } - } - } - - .stepper-connector { - flex: 1; - height: 1px; - margin: 0 8px; - background-color: rgba(0, 0, 0, .12); - transition: background-color 300ms ease; - - &.completed { - background-color: var(--tb-primary-500); - } - } - } - - .chat-container { - overflow: hidden; - min-height: 0; - } - - .chat-messages-container { - position: relative; - display: flex; - flex: 1 1 auto; - min-height: 0; - width: 100%; - max-width: min(800px, 100%); - } - - .chat { - flex: 1; - padding: 8px; - position: relative; - - & > * { - z-index: 1; - } - - &::before { - background: - radial-gradient(circle, rgba(0, 0, 0, 0.08) 1px, transparent 1px) 0 0 / 16px 16px repeat, - radial-gradient(185.49% 141.73% at -0.44% 0%, #FFF 40%, var(--tb-primary-100) 100%); - content: ""; - position: absolute; - inset: 0; - transition-duration: 600ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - transition-property: opacity; - opacity: 0; - } - - &.background { - &::before { - opacity: 1; - } - } - - .welcome-content { - position: absolute; - bottom: calc(50% + 16px); - left: 50%; - transform: translateX(-50%); - display: flex; - flex-direction: column; - align-items: center; - gap: 24px; - z-index: 1; - width: calc(100% - 16px); - } - - .action { - &.action-centered { - position: absolute; - top: 50%; - left: 50%; - transform: translateX(-50%); - width: calc(100% - 16px); - max-width: 800px; - } - - tb-ai-prompt-input { - max-width: 800px; - display: block; - } - - .tb-dynamic-button { - transition-duration: 600ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - transition-property: opacity; - opacity: 1; - - @starting-style { - opacity: 0; - } - } - - & > div { - max-width: 800px; - width: 100%; - } - } - - .example-chips { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 8px; - max-width: 670px !important; - max-height: 40px; - overflow: hidden; - transition: max-height 100ms ease; - --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; - - &.expanded { - max-height: 200px; - } - - .example-chip { - background-color: #fff; - } - } - - .more-toggle { - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.54); - --mat-button-text-container-height: 32px; - margin-top: -8px; - } - - .long-wait { - border: 1px solid rgba(0, 0, 0, 0.12); - padding: 40px; - animation: fadeInScale 0.3s ease-in-out forwards; - opacity: 0; - transform: scale(0.95); - - &.ng-leave { - animation: fadeOutScale 0.3s ease-in-out forwards; - } - - img { - width: 100px; - } - } - - } - - .overview { - flex: 0 0 0; - display: flex; - min-width: 0; - min-height: 0; - - &.entering { - animation: slide-in 400ms ease-in-out forwards; - transition-duration: 400ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - animation-name: slide-in; - transition-property: flex-basis; - } - - @keyframes slide-in { - from { - flex-basis: 0; - } - to { - flex-basis: 60%; - } - } - - } - } - - .solution-result { - .title { - font-size: 28px; - font-weight: 500; - line-height: 36px; - letter-spacing: 0.1px; - margin-bottom: 8px; - } - .sub-title { - font-size: 16px; - line-height: 24px; - letter-spacing: 0.2px; - } - .divider-text { - line-height: 20px; - font-size: 14px; - font-weight: 500; - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts deleted file mode 100644 index 153de939fb..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts +++ /dev/null @@ -1,733 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, computed, DestroyRef, ElementRef, OnDestroy, OnInit, signal, ViewChild } from '@angular/core'; -import { AiChatMessagesComponent } 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 { - ChatMessage, - DashboardsOverview, - SolutionCreatorInfo, - SolutionDescriptor, - SolutionInstallResult, - SolutionMetadata, - SolutionStep, - SolutionStepStatus -} from '@shared/models/solution-creator.models'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; -import { AiPromptMessage } from '@shared/models/ai-chat.models'; -import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; -import { - catchError, - filter, - finalize, - map, - switchMap, - takeUntil, - tap -} from 'rxjs/operators'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { EMPTY, Observable, of, Subject } from 'rxjs'; -import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { SolutionSideBarComponent } from '@home/pages/ai-solution-creator/side-bar/solution-side-bar.component'; -import { - SolutionInfoDialogComponent, - SolutionInfoDialogData -} from '@home/pages/ai-solution-creator/solution-info/solution-info-dialog.component'; -import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; -import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; -import { DynamicMatDialog } from '@shared/components/dialog/dynamic/dynamic-dialog'; -import { generatedStateImages } from '@home/components/ai/ai.models'; - -@Component({ - selector: 'tb-solution-creator', - templateUrl: './solution-creator.component.html', - styleUrls: ['./solution-creator.component.scss'], - standalone: false -}) -export class SolutionCreatorComponent extends PageComponent implements OnInit, OnDestroy { - - @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; - @ViewChild(AiChatMessagesComponent) chatMessages: AiChatMessagesComponent; - @ViewChild(SolutionSideBarComponent, {static: true}) solutionSideBar: SolutionSideBarComponent; - - isReadyStep = signal(false); - skipInterviewAllowed = signal(false); - solutionStep = signal(SolutionStep.INITIAL_CONFIGURATION); - creatorStep = signal<'chat' | 'result' | null>('chat'); - - messages = signal([]); - - loading = signal(false); - loadingLongTime = signal(false); - isGenerating = signal(false); - - showMoreExamples = signal(false); - - isInitialEmpty = computed(() => - this.creatorStep() === 'chat' && - this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION && - !this.messages().length && - !this.loading() - ); - - activePlaceholder = computed(() => - this.isInitialEmpty() ? 'solution-creator.describe-solution-you-want' : 'solution-creator.enter-your-prompt' - ); - - activeStepIndex = computed(() => { - if (!this.creatorStep()) { - return -1; - } - if (this.creatorStep() === 'result') { - return 2; - } - if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - return 1; - } - return 0; - }); - - stepperLabels: string[] = [ - 'solution-creator.step-architecture-design', - 'solution-creator.step-dashboard-design', - 'solution-creator.step-solution-installation', - ]; - - stepStatuses = signal>(['pending', 'pending', 'pending']); - - goToStep(index: number): void { - if (this.stepStatuses()[index] !== 'ready') { - return; - } - this.forceScroll = true; - if (index === 0) { - this.creatorStep.set('chat'); - this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); - this.updatedCurrentMsg(); - } else if (index === 1) { - this.creatorStep.set('chat'); - this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); - this.updatedCurrentMsg(); - } else if (index === 2) { - this.creatorStep.set('result'); - } - } - - private updateStepStatuses(): void { - const active = this.activeStepIndex(); - const statuses: Array<'ready' | 'active' | 'pending'> = [0, 1, 2].map(i => { - if (i === active) { - return 'active'; - } - if (!this.solutionInfo) { - return 'pending'; - } - if (i === 0 && this.solutionInfo.states?.[SolutionStep.INITIAL_CONFIGURATION]?.status === SolutionStepStatus.READY) { - return 'ready'; - } - if (i === 1 && this.solutionInfo.states?.[SolutionStep.DASHBOARDS_CONFIGURATION]?.status === SolutionStepStatus.READY) { - return 'ready'; - } - if (i === 2 && this.solutionInfo.metadata?.built) { - return 'ready'; - } - return 'pending'; - }); - this.stepStatuses.set(statuses); - } - - - solutionExamples: Array<{ key: string; labelKey: string; icon: string; message: string }> = [ - { - key: 'coffeeMonitor', - labelKey: 'solution-creator.coffee-machine-monitoring', - icon: 'local_cafe', - 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: 'sensors', - 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: 'wb_cloudy', - 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: 'directions_car', - 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; - solutionDescriptor: SolutionDescriptor; - dashboardsOverview: DashboardsOverview[]; - solutionName: string; - - loadingImage: string; - - private solutionId: string; - private _solutionInfo: SolutionCreatorInfo; - - private get solutionInfo(): SolutionCreatorInfo { - return this._solutionInfo; - } - - private set solutionInfo(value: SolutionCreatorInfo) { - this._solutionInfo = value; - this.updateStepStatuses(); - } - private messages$ = toObservable(this.messages); - private forceScroll = false; - - private cancelPending$ = new Subject(); - private loadingTimer: 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 dynamicMatDialog: DynamicMatDialog) { - super(); - - toObservable(this.activeStepIndex).pipe( - takeUntilDestroyed(), - ).subscribe(() => this.updateStepStatuses()); - - 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.chatMessages?.scrollToBottom('instant'); - }, { once: true }); - } else { - this.chatMessages?.scrollToBottom('instant'); - } - }, 0); - this.forceScroll = false; - } else if (lastMsg?.from === 'USER') { - setTimeout(() => this.chatMessages?.scrollToBottom('smooth'), 0); - } else if (lastMsg?.from === 'AI') { - setTimeout(() => this.chatMessages?.scrollToLastUserMessage(), 0); - } - }) - } - - ngOnInit() { - this.route.queryParams.pipe( - filter(data => this.solutionId !== data.solutionId), - tap(() => this.resetSolution()), - switchMap(data => { - if (data.solutionId) { - return this.solutionCreator.getSolutionById(data.solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( - catchError(err => { - this.creatorStep.set('chat'); - this.showErrorMessage(err); - return EMPTY; - }) - ); - } else { - this.creatorStep.set('chat'); - return EMPTY; - } - }), - takeUntilDestroyed(this.destroyRef) - ).subscribe(solution => { - this.solutionId = solution.id; - this.solutionInfo = solution; - this.forceScroll = true; - this.initPredefinedSolution(); - }); - } - - ngOnDestroy(): void { - this.cancelPending$.next(); - this.cancelPending$.complete(); - } - - nextStep() { - if(this.solutionInfo.states[this.solutionStep()]?.status === SolutionStepStatus.READY) { - if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { - const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; - if (!dashboardState) { - this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION] = { - messages: [], - status: SolutionStepStatus.IN_PROGRESS, - 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.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - if (this.solutionInfo.metadata?.built) { - this.creatorStep.set('result'); - } else { - const dialogRef = this.initGenerateState(); - const uninstallOrContinue$ = !this.solutionInfo.metadata?.installed - ? of(null) - : this.solutionCreator.uninstallSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}); - uninstallOrContinue$.pipe( - switchMap(() => this.solutionCreator.createSolution(this.solutionId, { - ignoreLoading: true, - ignoreErrors: true - })), - tap(() => this.creatorStep.set('result')), - switchMap((solution) => - this.solutionCreator.installSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}) - .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) => { - this.solutionInfo = value; - if (value.metadata.installResult.mainDashboardId) { - this.gotoMainDashboard(true); - } else { - this.openInfo(); - } - }, - error: (err) => { - this.showErrorMessage(err); - } - }); - } - } - } - } - - installSolution() { - const progressSubject = new Subject(); - this.dialogService.progress(progressSubject.asObservable(), this.translate.instant('solution-creator.installing')); - this.solutionCreator.installSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( - takeUntil(this.cancelPending$) - ).subscribe({ - next: (value) => { - 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.solutionSideBar.updateSolutionField({id: this.solutionId}, {installed: true}); - progressSubject.next(); - progressSubject.complete(); - if (value.mainDashboardId) { - this.gotoMainDashboard(true); - } else { - this.openInfo(); - } - }, - error: (err) => { - progressSubject.next(); - progressSubject.complete(); - this.showErrorMessage(err); - } - }); - } - - 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.solutionSideBar.updateSolutionField({id: this.solutionId}, {installed: false}); - }); - } - }) - } - - startOver() { - this.initLoadingState(); - this.solutionCreator.clearStep(this.solutionId, this.solutionStep(), {ignoreLoading: true, ignoreErrors: true}).pipe( - takeUntil(this.cancelPending$) - ).subscribe({ - next: () => { - this.messages.set([]); - 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(); - } - }) - } - - 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.solutionDescriptor = this.solutionInfo.data.solutionDescriptor; - }); - } - - updatedDashboardOverview(dashboards: DashboardsOverview[]) { - this.solutionCreator.updateSolutionData(this.solutionId, 'dashboardsOverview', dashboards, {ignoreLoading: true}).pipe( - takeUntil(this.cancelPending$) - ).subscribe(value => { - this.solutionInfo = value; - this.dashboardsOverview = this.solutionInfo.data.dashboardsOverview; - }); - } - - 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.solutionName = $event.data?.solutionTitle; - 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: []}); - } - } - - 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.solutionId = solution.id; - this.solutionInfo = solution; - 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.solutionInfo = solution; - this.solutionSideBar.addNewSolutionTemplate({id: this.solutionId, solutionTitle: this.solutionInfo?.data?.solutionTitle ?? '', built: this.solutionInfo?.metadata?.built, installed: this.solutionInfo?.metadata?.installed}); - this.updatedCurrentMsg(); - }), - catchError(err => { - this.showErrorMessage(err); - this.solutionSideBar.addNewSolutionTemplate({id: this.solutionId, solutionTitle: this.solutionInfo?.data?.solutionTitle ?? '', built: this.solutionInfo?.metadata?.built, installed: this.solutionInfo?.metadata?.installed}); - return EMPTY; - }), - takeUntil(this.cancelPending$), - finalize(() => this.stopLoadingState()) - ); - } - - private sendDashboardConfigurationMsg(message: string): void { - const dialogRef = this.initGenerateState(); - this.sendMessage(message).pipe( - finalize(() => { - this.isGenerating.set(false); - dialogRef.close(); - }), - ).subscribe(() => {}); - } - - private updatedCurrentMsg() { - this.messages.set(this.solutionInfo.states[this.solutionStep()]?.messages?.filter(msg => msg.from === 'AI' || msg.from === 'USER') ?? []); - const stepState = this.solutionInfo.states[this.solutionStep()]; - if (stepState?.status === SolutionStepStatus.READY) { - this.solutionName = this.solutionInfo.data?.solutionTitle; - if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { - this.solutionDescriptor = this.solutionInfo.data.solutionDescriptor; - } - if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - this.dashboardsOverview = this.solutionInfo.data.dashboardsOverview; - } - 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 resetSolution(): void { - this.cancelPending$.next(); - this.isReadyStep.set(false); - this.skipInterviewAllowed.set(false); - this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); - this.messages.set([]); - this.stopLoadingState(); - this.creatorStep.set(null); - this.promptInput?.reset(); - this.showMoreExamples.set(false); - this.solutionDescriptor = undefined; - this.solutionId = undefined; - this.solutionInfo = undefined; - this.solutionName = undefined; - } - - private initPredefinedSolution(): void { - if (this.solutionInfo.metadata?.built) { - this.creatorStep.set('result'); - return; - } - this.creatorStep.set('chat'); - const initialStatus = this.solutionInfo.states[SolutionStep.INITIAL_CONFIGURATION]?.status; - const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; - if (initialStatus === SolutionStepStatus.READY && dashboardState) { - this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); - } - this.updatedCurrentMsg(); - if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION && dashboardState?.pendingChanges?.length) { - this.sendDashboardConfigurationMsg(''); - } - } - - private initGenerateState() { - this.isGenerating.set(true); - let messages: Array<{text: string; delay: number}>; - let estimateWaitTime: number; - if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { - estimateWaitTime = 30000; - 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 (!this.messages().length) { - estimateWaitTime = 30000; - 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 (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]?.pendingChanges?.length) { - estimateWaitTime = 20000; - 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 { - estimateWaitTime = 90000; - 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 }, - ]; - } - } - - return this.dynamicMatDialog.open(AiLoadingModalComponent, { - containerElement: this.elementRef.nativeElement, - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - backdropClass: 'ai-backdrop-filter', - data: { - messages, - estimateWaitTime, - } - }); - } - - toggleMoreExamples(): void { - this.showMoreExamples.update(v => !v); - } - - skipInterview(): void { - this.sendMessage('').subscribe(() => {}); - } - - sendMsgFromUser(prompt: AiPromptMessage): void { - this.messages.update(list => [...list, prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources} - : {from: 'USER', content: prompt.message}]); - this.sendMessage(prompt.message, prompt.resources.map(resource => resource.id)).subscribe(() => {}); - } - - private initLoadingState(): void { - this.loading.set(true); - this.loadingImage = generatedStateImages[Math.floor(Math.random() * generatedStateImages.length)]; - this.loadingTimer = setTimeout(() => { - this.loadingLongTime.set(true); - }, 5000); - } - - private stopLoadingState(): void { - this.loading.set(false); - this.loadingLongTime.set(false); - clearTimeout(this.loadingTimer); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts deleted file mode 100644 index 26ea5ee7a3..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts +++ /dev/null @@ -1,51 +0,0 @@ -// 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 { SolutionCreatorComponent } from '@home/pages/ai-solution-creator/solution-creator.component'; -import { SolutionCreatorRoutingModule } from '@home/pages/ai-solution-creator/solution-creator-routing.module'; -import { - SolutionCreatorOverviewEntitiesComponent -} from '@home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component'; -import { AlarmInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/alarm-info-panel.component'; -import { EntityInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/entity-info-panel.component'; -import { IamInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/iam-info-panel.component'; -import { MetricInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/metric-info-panel.component'; -import { - SolutionCreatorOverviewDashboardComponent -} from '@home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component'; -import { SolutionSideBarComponent } from '@home/pages/ai-solution-creator/side-bar/solution-side-bar.component'; -import { - SolutionInfoDialogComponent -} from '@home/pages/ai-solution-creator/solution-info/solution-info-dialog.component'; -import { - IssuesPopoverComponent -} from '@home/pages/ai-solution-creator/solution-info/issues-popover.component'; -import { NgxGraphModule } from '@swimlane/ngx-graph'; -import { AiModule } from '@home/components/ai/ai.module'; - -@NgModule({ - declarations: [ - SolutionCreatorComponent, - SolutionCreatorOverviewEntitiesComponent, - AlarmInfoPanelComponent, - EntityInfoPanelComponent, - MetricInfoPanelComponent, - IamInfoPanelComponent, - SolutionCreatorOverviewDashboardComponent, - SolutionSideBarComponent, - SolutionInfoDialogComponent, - IssuesPopoverComponent - ], - imports: [ - CommonModule, - SharedModule, - HomeComponentsModule, - SolutionCreatorRoutingModule, - NgxGraphModule, - AiModule - ] -}) -export class SolutionCreatorModule { } diff --git a/ui-ngx/src/app/modules/home/pages/alarm/alarm-routing.module.ts b/ui-ngx/src/app/modules/home/pages/alarm/alarm-routing.module.ts index 372263326b..f1520b076d 100644 --- a/ui-ngx/src/app/modules/home/pages/alarm/alarm-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/alarm/alarm-routing.module.ts @@ -24,7 +24,6 @@ import { EntityDebugSettingsService } from '@home/components/entity/debug/entity import { UtilsService } from '@core/services/utils.service'; import { AlarmRulesTableConfig } from '@home/components/alarm-rules/alarm-rules-table-config'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { AiAssistantAlarmButtonComponent } from '@home/components/alarm/ai-assistant-alarm-button.component'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; export const AlarmRulesTableConfigResolver: ResolveFn = @@ -74,8 +73,7 @@ const routes: Routes = [ auth: [Authority.TENANT_ADMIN, Authority.CUSTOMER_USER], breadcrumb: { menuId: MenuId.alarms_center - }, - routerTabsHeaderComponent: AiAssistantAlarmButtonComponent + } }, children: [ { diff --git a/ui-ngx/src/app/modules/home/pages/asset-profile/asset-profiles-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/asset-profile/asset-profiles-table-config.resolver.ts index 971976f4e5..7cb42670b6 100644 --- a/ui-ngx/src/app/modules/home/pages/asset-profile/asset-profiles-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/asset-profile/asset-profiles-table-config.resolver.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { Router } from '@angular/router'; import { checkBoxCell, @@ -29,6 +31,8 @@ export class AssetProfilesTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private assetProfileService: AssetProfileService, private importExport: ImportExportService, private userPermissionsService: UserPermissionsService, @@ -96,6 +100,7 @@ export class AssetProfilesTableConfigResolver { resolve(): EntityTableConfig { this.config.tableTitle = this.translate.instant('asset-profile.asset-profiles'); defaultEntityTablePermissions(this.userPermissionsService, this.config); + this.config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.ASSET_PROFILE_LIST, AiAssistantViewType.ASSET_PROFILE); return this.config; } diff --git a/ui-ngx/src/app/modules/home/pages/asset/asset-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/asset/asset-group-config.factory.ts index 0bcf331563..8ff9546a9c 100644 --- a/ui-ngx/src/app/modules/home/pages/asset/asset-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/asset/asset-group-config.factory.ts @@ -8,7 +8,9 @@ import { EntityGroupStateInfo, GroupEntityTableConfig } from '@home/models/group/group-entities-table-config.models'; -import { Inject, Injectable } from '@angular/core'; +import { Inject, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { EntityType } from '@shared/models/entity-type.models'; import { mergeMap, tap } from 'rxjs/operators'; import { BroadcastService } from '@core/services/broadcast.service'; @@ -29,6 +31,8 @@ import { WINDOW } from '@core/services/window.service'; @Injectable() export class AssetGroupConfigFactory implements EntityGroupStateConfigFactory { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private groupConfigTableConfigService: GroupConfigTableConfigService, private userPermissionsService: UserPermissionsService, private translate: TranslateService, @@ -76,6 +80,7 @@ export class AssetGroupConfigFactory implements EntityGroupStateConfigFactory, private store: Store, private broadcast: BroadcastService, @@ -86,6 +90,7 @@ export class AssetsTableConfigResolver { config.cellActionDescriptors = this.configureCellActions(config); config.groupActionDescriptors = this.configureGroupActions(config); config.addActionDescriptors = this.configureAddActions(config); + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.ASSET_LIST, AiAssistantViewType.ASSET); return this.allEntitiesTableConfigService.prepareConfiguration(config); }) ); diff --git a/ui-ngx/src/app/modules/home/pages/calculated-fields/calculated-fields-routing.module.ts b/ui-ngx/src/app/modules/home/pages/calculated-fields/calculated-fields-routing.module.ts index 6b12faf6a0..96377952d9 100644 --- a/ui-ngx/src/app/modules/home/pages/calculated-fields/calculated-fields-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/calculated-fields/calculated-fields-routing.module.ts @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { DestroyRef, inject, NgModule } from '@angular/core'; -import { ActivatedRouteSnapshot, ResolveFn, Router, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, CanActivateFn, ResolveFn, Router, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; import { Authority } from '@shared/models/authority.enum'; import { MenuId } from '@core/services/menu.models'; import { CalculatedFieldsTableComponent } from '@home/components/calculated-fields/calculated-fields-table.component'; @@ -22,6 +22,21 @@ import { EntityDebugSettingsService } from '@home/components/entity/debug/entity import { UtilsService } from '@core/services/utils.service'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { CalculatedFieldType } from '@shared/models/calculated-field.models'; +import { of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; + +export const calculatedFieldPageGuard: CanActivateFn = (route: ActivatedRouteSnapshot) => { + const router = inject(Router); + const entityId = route.paramMap.get('entityId'); + if (!entityId) { + return true; + } + return inject(CalculatedFieldsService).getCalculatedFieldById(entityId, {ignoreErrors: true, ignoreLoading: true}).pipe( + map(field => field?.type === CalculatedFieldType.ALARM ? router.createUrlTree(['/alarms/alarm-rules', entityId]) : true), + catchError(() => of(true)) + ); +}; export const CalculatedFieldsTableConfigResolver: ResolveFn = (_route: ActivatedRouteSnapshot, @@ -84,6 +99,7 @@ const routes: Routes = [ { path: ':entityId', component: EntityDetailsPageComponent, + canActivate: [calculatedFieldPageGuard], canDeactivate: [ConfirmOnExitGuard], data: { breadcrumb: { diff --git a/ui-ngx/src/app/modules/home/pages/converter/converters-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/converter/converters-table-config.resolver.ts index 4f2a95806f..21dd956121 100644 --- a/ui-ngx/src/app/modules/home/pages/converter/converters-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/converter/converters-table-config.resolver.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { DestroyRef, Injectable } from '@angular/core'; +import { DestroyRef, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { DateEntityTableColumn, @@ -41,6 +43,8 @@ export class ConvertersTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private converterService: ConverterService, private userPermissionsService: UserPermissionsService, private translate: TranslateService, @@ -135,6 +139,9 @@ export class ConvertersTableConfigResolver { this.config.entitiesFetchFunction = this.configureEntityFunctions(this.config.componentsData.converterScope); defaultEntityTablePermissions(this.userPermissionsService, this.config); + this.config.aiAssistantConfig = this.config.componentsData.converterScope === 'edges' + ? this.aiAssistantConfigService.tableConfig(AiAssistantViewType.CONVERTER_TEMPLATE_LIST, AiAssistantViewType.CONVERTER_TEMPLATE) + : this.aiAssistantConfigService.tableConfig(AiAssistantViewType.CONVERTER_LIST, AiAssistantViewType.CONVERTER); return this.config; } diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts index 6fbef50183..5ff3f81509 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts @@ -1,12 +1,16 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, ElementRef, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; +import { Component, DestroyRef, ElementRef, inject, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { filter, switchMap, tap } from 'rxjs/operators'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActivatedRoute, Router } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; import { + afterLoadCustomMenuConfig, beforeSaveCustomMenuConfig, CustomMenuConfig, CustomMenuInfo, @@ -73,6 +77,9 @@ export class CustomMenuConfigComponent extends PageComponent implements OnInit, return !this.readonly && this.visibleMenuItemsControls().length > 1; } + private aiAssistantPanelService = inject(AiAssistantPanelService); + private destroyRef = inject(DestroyRef); + constructor(protected store: Store, private fb: UntypedFormBuilder, private router: Router, @@ -99,6 +106,21 @@ export class CustomMenuConfigComponent extends PageComponent implements OnInit, this.computeMaxIconNameBlockWidth(); }); this.computeMaxIconNameBlockWidth(); + this.aiAssistantPanelService.customizationReload$('MENU').pipe( + filter(event => event.menuId === this.customMenu.id.id), + tap(event => { + if (event.deleted) { + this.forcePristine = true; + this.goBack(); + } + }), + filter(event => !event.deleted && !this.isDirty), + switchMap(() => this.customMenuService.getCustomMenuConfig(this.customMenu.id.id)), + takeUntilDestroyed(this.destroyRef) + ).subscribe(config => { + this.customMenuConfig = afterLoadCustomMenuConfig(config, this.customMenu.scope); + this.cancel(); + }); } ngOnDestroy() { diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts index 280fbfad07..b63cc50ae2 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, OnInit, Renderer2, ViewContainerRef } from '@angular/core'; +import { Component, DestroyRef, inject, OnInit, Renderer2, ViewContainerRef } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { TranslateService } from '@ngx-translate/core'; import { DatePipe } from '@angular/common'; import { MatDialog } from '@angular/material/dialog'; @@ -66,7 +68,15 @@ export class CustomMenuTableComponent implements OnInit { private viewContainerRef: ViewContainerRef) { } + private aiAssistantPanelService = inject(AiAssistantPanelService); + private destroyRef = inject(DestroyRef); + ngOnInit() { + this.aiAssistantPanelService.customizationReload$('MENU').pipe( + takeUntilDestroyed(this.destroyRef) + ).subscribe(() => { + this.customMenuTableConfig.updateData(); + }); this.customMenuTableConfig.tableTitle = ''; this.customMenuTableConfig.headerComponent = CustomMenuTableHeaderComponent; this.customMenuTableConfig.detailsPanelEnabled = false; diff --git a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts index cd70f2ab7b..caf4c64770 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts @@ -6,6 +6,7 @@ import { Component, ElementRef, EventEmitter, + inject, Input, NgZone, OnDestroy, OnInit, @@ -13,6 +14,7 @@ import { ViewChild } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { MatSort, SortDirection } from '@angular/material/sort'; import { PageLink, PageQueryParam } from '@shared/models/page/page-link'; import { BehaviorSubject, forkJoin, merge, Observable, of, Subject } from 'rxjs'; @@ -22,7 +24,7 @@ import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { CustomTranslationService } from '@core/http/custom-translation.service'; import { ActivatedRoute, QueryParamsHandling, Router } from '@angular/router'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { catchError, debounceTime, distinctUntilChanged, map, skip, takeUntil } from 'rxjs/operators'; +import { catchError, debounceTime, distinctUntilChanged, filter, map, skip, takeUntil } from 'rxjs/operators'; import { isDefinedAndNotNull, isEqual, isNotEmptyStr, setByPath, unset } from '@core/utils'; import { DataSource } from '@angular/cdk/collections'; import { emptyPageData, PageData } from '@shared/models/page/page-data'; @@ -99,6 +101,7 @@ export class TranslationMapTableComponent extends PageComponent implements OnIni private tableResize$: ResizeObserver; private destroy$ = new Subject(); + private aiAssistantPanelService = inject(AiAssistantPanelService); private defaultSortOrder: SortOrder = { property: 'k', direction: Direction.ASC }; constructor(protected store: Store, @@ -140,6 +143,10 @@ export class TranslationMapTableComponent extends PageComponent implements OnIni this.paginator.pageIndex = this.pageLink.page; this.paginator.pageSize = this.pageLink.pageSize; this.dataSource.loadTranslateInfo(this.pageLink, this.filterParams.value); + this.aiAssistantPanelService.customizationReload$('TRANSLATION').pipe( + filter(event => event.locale === this.localeCode), + takeUntil(this.destroy$) + ).subscribe(() => this.updateData(true)); this.initSubscriptions(); this.newKey = this.fb.group({ diff --git a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts index a9c4dcd787..db958cd901 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; +import { ChangeDetectionStrategy, Component, ElementRef, inject, OnDestroy, OnInit, ViewChild } from '@angular/core'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { TranslateService } from '@ngx-translate/core'; import { MatDialog } from '@angular/material/dialog'; import { CustomTranslationService } from '@core/http/custom-translation.service'; @@ -51,6 +52,8 @@ export class TranslationTableComponent extends PageComponent implements OnInit, private destroy$ = new Subject(); + private aiAssistantPanelService = inject(AiAssistantPanelService); + constructor(protected store: Store, private fb: FormBuilder, private customTranslationService: CustomTranslationService, @@ -72,6 +75,9 @@ export class TranslationTableComponent extends PageComponent implements OnInit, this.sort.active = this.pageLink.sortOrder.property; this.sort.direction = (this.pageLink.sortOrder.direction).toLowerCase() as SortDirection; this.dataSource.loadTranslateInfo(this.pageLink); + this.aiAssistantPanelService.customizationReload$('TRANSLATION').pipe( + takeUntil(this.destroy$) + ).subscribe(() => this.updateData(true)); this.textSearch.valueChanges.pipe( debounceTime(150), distinctUntilChanged((prev, current) => (this.pageLink.textSearch ?? '') === current.trim()), diff --git a/ui-ngx/src/app/modules/home/pages/customer/customer-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/customer/customer-group-config.factory.ts index 16cdd33799..086327193c 100644 --- a/ui-ngx/src/app/modules/home/pages/customer/customer-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/customer/customer-group-config.factory.ts @@ -8,7 +8,9 @@ import { EntityGroupStateInfo, GroupEntityTableConfig } from '@home/models/group/group-entities-table-config.models'; -import { Inject, Injectable } from '@angular/core'; +import { Inject, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { EntityAction } from '@home/models/entity/entity-component.models'; import { MatDialog } from '@angular/material/dialog'; import { UserPermissionsService } from '@core/http/user-permissions.service'; @@ -30,6 +32,8 @@ import { mergeMap } from 'rxjs/operators'; @Injectable() export class CustomerGroupConfigFactory implements EntityGroupStateConfigFactory { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private groupConfigTableConfigService: GroupConfigTableConfigService, private userPermissionsService: UserPermissionsService, private translate: TranslateService, @@ -157,6 +161,9 @@ export class CustomerGroupConfigFactory implements EntityGroupStateConfigFactory ); } + config.aiAssistantConfig = config.entityGroup && !config.entityGroup.groupAll + ? this.aiAssistantConfigService.tableConfig(AiAssistantViewType.CUSTOMER_GROUP, AiAssistantViewType.CUSTOMER, config.entityGroup.id) + : this.aiAssistantConfigService.tableConfig(AiAssistantViewType.CUSTOMER_LIST, AiAssistantViewType.CUSTOMER); return this.groupConfigTableConfigService.prepareConfiguration(params, config); } diff --git a/ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts index 6f6725d9a9..b78a773ee3 100644 --- a/ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/customer/customers-table-config.resolver.ts @@ -1,8 +1,10 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { @@ -42,6 +44,8 @@ import { AuthState } from '@core/auth/auth.models'; @Injectable() export class CustomersTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private allEntitiesTableConfigService: AllEntitiesTableConfigService, private userPermissionsService: UserPermissionsService, private customerService: CustomerService, @@ -81,6 +85,7 @@ export class CustomersTableConfigResolver { config.cellActionDescriptors = this.configureCellActions(config, authState); config.groupActionDescriptors = this.configureGroupActions(config); config.addActionDescriptors = this.configureAddActions(config); + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.CUSTOMER_LIST, AiAssistantViewType.CUSTOMER); return this.allEntitiesTableConfigService.prepareConfiguration(config); }) ); diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts index 4b6e7a93f0..75730a2d09 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts @@ -8,7 +8,9 @@ import { EntityGroupStateInfo, GroupEntityTableConfig } from '@home/models/group/group-entities-table-config.models'; -import { Inject, Injectable } from '@angular/core'; +import { Inject, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityAction } from '@home/models/entity/entity-component.models'; import { MatDialog } from '@angular/material/dialog'; @@ -22,7 +24,6 @@ import { DashboardService } from '@core/http/dashboard.service'; import { DashboardUtilsService } from '@core/services/dashboard-utils.service'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { DashboardFormComponent } from '@home/pages/dashboard/dashboard-form.component'; import { Operation, Resource } from '@shared/models/security.models'; import { ImportExportService } from '@shared/import-export/import-export.service'; @@ -44,6 +45,8 @@ import { @Injectable() export class DashboardGroupConfigFactory implements EntityGroupStateConfigFactory { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private groupConfigTableConfigService: GroupConfigTableConfigService, private userPermissionsService: UserPermissionsService, private translate: TranslateService, @@ -143,18 +146,9 @@ export class DashboardGroupConfigFactory implements EntityGroupStateConfigFactor onAction: ($event) => this.importDashboard($event, config) } ); - if (getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { - config.headerButtonDescriptors.push( - { - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.generateWithAi($event, config, params) - } - ); - } + config.headerActionDescriptors.push(...this.aiAssistantConfigService.configureAction($event => this.generateWithAi($event, config, params))); } + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.DASHBOARD_GROUP, undefined, config.entityGroup.id); return this.groupConfigTableConfigService.prepareConfiguration(params, config); } diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts index c63b23a9ce..e7802ec29b 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { @@ -20,7 +22,7 @@ import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared import { EntityAction } from '@home/models/entity/entity-component.models'; import { Observable, of } from 'rxjs'; import { Store } from '@ngrx/store'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { map, mergeMap } from 'rxjs/operators'; import { AppState } from '@core/core.state'; import { Authority } from '@app/shared/models/authority.enum'; @@ -46,12 +48,13 @@ import { } from '@home/components/alias/entity-aliases-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { DashboardUtilsService } from '@core/services/dashboard-utils.service'; @Injectable() export class DashboardsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private allEntitiesTableConfigService: AllEntitiesTableConfigService, private store: Store, private userPermissionsService: UserPermissionsService, @@ -98,6 +101,12 @@ export class DashboardsTableConfigResolver { config.tableTitle = this.translate.instant('dashboard.dashboards'); } config.columns = this.configureColumns(authUser, config); + if (this.userPermissionsService.isAiAvailable()) { + config.aiAssistantConfig = { + view: {listView: AiAssistantViewType.DASHBOARD_LIST, entityView: AiAssistantViewType.DASHBOARD}, + initialPromptPlaceholder: this.translate.instant('dashboard.ai-assistant-initial-prompt-placeholder') + }; + } this.configureEntityFunctions(config); config.cellActionDescriptors = this.configureCellActions(config); config.groupActionDescriptors = this.configureGroupActions(config); @@ -136,17 +145,6 @@ export class DashboardsTableConfigResolver { config.entityAdded = dashboard => { this.openDashboard(null, dashboard, config); }; - - if (getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - this.userPermissionsService.hasGenericPermission(Resource.DASHBOARD, Operation.CREATE)) { - config.headerButtonDescriptors.push({ - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.generateWithAi($event, config) - }); - } } configureColumns(authUser: AuthUser, config: EntityTableConfig): Array> { @@ -205,7 +203,7 @@ export class DashboardsTableConfigResolver { } configureAddActions(config: EntityTableConfig): Array { - return [ + const actions: Array = [ { name: this.translate.instant('dashboard.create-new-dashboard'), icon: 'insert_drive_file', @@ -219,6 +217,8 @@ export class DashboardsTableConfigResolver { onAction: ($event) => this.importDashboard($event, config) } ]; + actions.push(...this.aiAssistantConfigService.configureAction($event => this.generateWithAi($event, config))); + return actions; } generateWithAi($event: Event, config: EntityTableConfig) { diff --git a/ui-ngx/src/app/modules/home/pages/device-profile/device-profiles-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/device-profile/device-profiles-table-config.resolver.ts index 1f92f2286b..36e843cac1 100644 --- a/ui-ngx/src/app/modules/home/pages/device-profile/device-profiles-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/device-profile/device-profiles-table-config.resolver.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { Router } from '@angular/router'; import { checkBoxCell, @@ -39,6 +41,8 @@ export class DeviceProfilesTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private deviceProfileService: DeviceProfileService, private importExport: ImportExportService, private userPermissionsService: UserPermissionsService, @@ -118,6 +122,7 @@ export class DeviceProfilesTableConfigResolver { resolve(): EntityTableConfig { this.config.tableTitle = this.translate.instant('device-profile.device-profiles'); defaultEntityTablePermissions(this.userPermissionsService, this.config); + this.config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.DEVICE_PROFILE_LIST, AiAssistantViewType.DEVICE_PROFILE); return this.config; } diff --git a/ui-ngx/src/app/modules/home/pages/edge/edge-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/edge/edge-group-config.factory.ts index 5547238815..69a9f27af7 100644 --- a/ui-ngx/src/app/modules/home/pages/edge/edge-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/edge/edge-group-config.factory.ts @@ -8,7 +8,7 @@ import { EntityGroupStateInfo, GroupEntityTableConfig } from '@home/models/group/group-entities-table-config.models'; -import { Inject, Injectable } from '@angular/core'; +import { Inject, Injectable, inject } from '@angular/core'; import { EntityType } from '@shared/models/entity-type.models'; import { mergeMap, tap } from 'rxjs/operators'; import { BroadcastService } from '@core/services/broadcast.service'; @@ -35,10 +35,14 @@ import { EdgeInstructionsDialogComponent, EdgeInstructionsDialogData } from '@home/pages/edge/edge-instructions-dialog.component'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; @Injectable() export class EdgeGroupConfigFactory implements EntityGroupStateConfigFactory { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private groupConfigTableConfigService: GroupConfigTableConfigService, private userPermissionsService: UserPermissionsService, private store: Store, @@ -58,6 +62,7 @@ export class EdgeGroupConfigFactory implements EntityGroupStateConfigFactory edge ? diff --git a/ui-ngx/src/app/modules/home/pages/edge/edges-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/edge/edges-table-config.resolver.ts index b0bcf69ce9..66f09ed6f0 100644 --- a/ui-ngx/src/app/modules/home/pages/edge/edges-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/edge/edges-table-config.resolver.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 { Injectable } from '@angular/core'; +import { Injectable, inject } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { @@ -54,10 +54,14 @@ import { AgentAutoProvisionDialogComponent } from '@home/components/agent/dialog/agent-auto-provision-dialog.component'; import { AgentApplicationType } from '@shared/models/agent.models'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; @Injectable() export class EdgesTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private allEntitiesTableConfigService: AllEntitiesTableConfigService, private userPermissionsService: UserPermissionsService, private store: Store, @@ -102,6 +106,7 @@ export class EdgesTableConfigResolver { config.groupActionDescriptors = this.configureGroupActions(config); config.addActionDescriptors = this.configureAddActions(config); config.addEntity = () => { this.addEdge(config); return of(null); }; + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.EDGE_LIST, AiAssistantViewType.EDGE); return this.allEntitiesTableConfigService.prepareConfiguration(config); }) ); diff --git a/ui-ngx/src/app/modules/home/pages/entity-view/entity-view-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/entity-view/entity-view-group-config.factory.ts index ff31ecd58c..5b08941fd2 100644 --- a/ui-ngx/src/app/modules/home/pages/entity-view/entity-view-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/entity-view/entity-view-group-config.factory.ts @@ -8,7 +8,9 @@ import { EntityGroupStateInfo, GroupEntityTableConfig } from '@home/models/group/group-entities-table-config.models'; -import { Inject, Injectable } from '@angular/core'; +import { Inject, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { mergeMap, tap } from 'rxjs/operators'; import { BroadcastService } from '@core/services/broadcast.service'; import { EntityAction } from '@home/models/entity/entity-component.models'; @@ -27,6 +29,8 @@ import { WINDOW } from '@core/services/window.service'; @Injectable() export class EntityViewGroupConfigFactory implements EntityGroupStateConfigFactory { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private groupConfigTableConfigService: GroupConfigTableConfigService, private userPermissionsService: UserPermissionsService, private translate: TranslateService, @@ -66,6 +70,7 @@ export class EntityViewGroupConfigFactory implements EntityGroupStateConfigFacto config.onEntityAction = action => this.onEntityViewAction(action, config, params); + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.ENTITY_VIEW_GROUP, AiAssistantViewType.ENTITY_VIEW, config.entityGroup.id); return this.groupConfigTableConfigService.prepareConfiguration(params, config); } diff --git a/ui-ngx/src/app/modules/home/pages/entity-view/entity-views-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/entity-view/entity-views-table-config.resolver.ts index 1c4ebb0237..0407dae8ad 100644 --- a/ui-ngx/src/app/modules/home/pages/entity-view/entity-views-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/entity-view/entity-views-table-config.resolver.ts @@ -1,8 +1,10 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { CellActionDescriptor, @@ -44,6 +46,8 @@ import { HomeDialogsService } from '@home/dialogs/home-dialogs.service'; @Injectable() export class EntityViewsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private allEntitiesTableConfigService: AllEntitiesTableConfigService, private store: Store, private broadcast: BroadcastService, @@ -87,6 +91,7 @@ export class EntityViewsTableConfigResolver { config.cellActionDescriptors = this.configureCellActions(config); config.groupActionDescriptors = this.configureGroupActions(config); config.addActionDescriptors = this.configureAddActions(config); + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.ENTITY_VIEW_LIST, AiAssistantViewType.ENTITY_VIEW); return this.allEntitiesTableConfigService.prepareConfiguration(config); }) ); diff --git a/ui-ngx/src/app/modules/home/pages/home-links/home-links-routing.module.ts b/ui-ngx/src/app/modules/home/pages/home-links/home-links-routing.module.ts deleted file mode 100644 index 0e8ee61443..0000000000 --- a/ui-ngx/src/app/modules/home/pages/home-links/home-links-routing.module.ts +++ /dev/null @@ -1,159 +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 { inject, NgModule } from '@angular/core'; -import { ActivatedRouteSnapshot, ResolveFn, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; - -import { HomeLinksComponent } from './home-links.component'; -import { Authority } from '@shared/models/authority.enum'; -import { mergeMap, Observable, of } from 'rxjs'; -import { HomeDashboard } from '@shared/models/dashboard.models'; -import { DashboardService } from '@core/http/dashboard.service'; -import { select, Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { catchError, first, map } from 'rxjs/operators'; -import { - getCurrentAuthUser, - selectHomeDashboardParams, - selectMobileQrEnabled, - selectPersistDeviceStateToTelemetry -} from '@core/auth/auth.selectors'; -import { EntityKeyType } from '@shared/models/query/query.models'; -import { ResourcesService } from '@core/services/resources.service'; -import { isDefinedAndNotNull } from '@core/utils'; -import { MenuId } from '@core/services/menu.models'; -import { MenuService } from '@core/services/menu.service'; - -const sysAdminHomePageJson = '/assets/dashboard/sys_admin_home_page.json'; -const tenantAdminHomePageJson = '/assets/dashboard/tenant_admin_home_page.json'; -// const customerUserHomePageJson = '/assets/dashboard/customer_user_home_page.json'; - -const getHomeDashboard = (store: Store, resourcesService: ResourcesService) => { - const authority = getCurrentAuthUser(store).authority; - switch (authority) { - case Authority.SYS_ADMIN: - return applySystemParametersToHomeDashboard(store, resourcesService.loadJsonResource(sysAdminHomePageJson), authority); - case Authority.TENANT_ADMIN: - return applySystemParametersToHomeDashboard(store, resourcesService.loadJsonResource(tenantAdminHomePageJson), authority); - // case Authority.CUSTOMER_USER: - // return applySystemParametersToHomeDashboard(store, resourcesService.loadJsonResource(customerUserHomePageJson), authority); - default: - return of(null); - } -}; - -const applySystemParametersToHomeDashboard = (store: Store, - dashboard$: Observable, - authority: Authority): Observable => { - let selectParams$: Observable<{persistDeviceStateToTelemetry?: boolean; mobileQrEnabled?: boolean}>; - switch (authority) { - case Authority.SYS_ADMIN: - selectParams$ = store.pipe( - select(selectMobileQrEnabled), - map(mobileQrEnabled => ({mobileQrEnabled})) - ); - break; - case Authority.TENANT_ADMIN: - selectParams$ = store.pipe(select(selectHomeDashboardParams)); - break; - case Authority.CUSTOMER_USER: - selectParams$ = store.pipe( - select(selectPersistDeviceStateToTelemetry), - map(persistDeviceStateToTelemetry => ({persistDeviceStateToTelemetry})) - ); - break; - } - return selectParams$.pipe( - mergeMap((params) => dashboard$.pipe( - map((dashboard) => { - if (params.persistDeviceStateToTelemetry) { - for (const filterId of Object.keys(dashboard.configuration.filters)) { - if (['Active Devices', 'Inactive Devices'].includes(dashboard.configuration.filters[filterId].filter)) { - dashboard.configuration.filters[filterId].keyFilters[0].key.type = EntityKeyType.TIME_SERIES; - } - } - } - if (isDefinedAndNotNull(params.mobileQrEnabled)) { - for (const widgetId of Object.keys(dashboard.configuration.widgets)) { - if (dashboard.configuration.widgets[widgetId].config.title === 'Select show mobile QR code') { - dashboard.configuration.widgets[widgetId].config.settings.markdownTextFunction = - (dashboard.configuration.widgets[widgetId].config.settings.markdownTextFunction as string) - .replace(/\${mobileQrEnabled:([^}]+)}/, `\${mobileQrEnabled:${String(params.mobileQrEnabled)}}`); - break; - } - } - } - dashboard.hideDashboardToolbar = true; - dashboard.isSystemDashboard = true; - return dashboard; - }) - )) - ); -}; - -const resolveMenuHomeDashboard = (menuService: MenuService, - dashboardService: DashboardService, - resourcesService: ResourcesService, - store: Store): Observable => - menuService.menuSections().pipe(first()).pipe( - mergeMap((sections) => { - const homeSection = sections.find(s => s.id === MenuId.home); - if (homeSection?.homeDashboardId) { - return dashboardService.getDashboard(homeSection.homeDashboardId, {ignoreErrors: true}).pipe( - map((dashboard) => ({ - ...dashboard, - hideDashboardToolbar: homeSection.homeHideDashboardToolbar - })), - catchError(() => getHomeDashboard(store, resourcesService)) - ); - } else { - return getHomeDashboard(store, resourcesService); - } - }) - ); - -const resolveHomeDashboard = (menuService: MenuService, - dashboardService: DashboardService, - resourcesService: ResourcesService, - store: Store): Observable => - dashboardService.getHomeDashboard().pipe( - mergeMap((dashboard) => { - if (!dashboard) { - return resolveMenuHomeDashboard(menuService, dashboardService, resourcesService, store); - } - return of(dashboard); - }), - catchError(() => resolveMenuHomeDashboard(menuService, dashboardService, resourcesService, store)) - ); - -export const homeDashboardResolver: ResolveFn = ( - _route: ActivatedRouteSnapshot, - _state: RouterStateSnapshot, - menuService = inject(MenuService), - dashboardService = inject(DashboardService), - resourcesService = inject(ResourcesService), - store: Store = inject(Store) -): Observable => resolveHomeDashboard(menuService, dashboardService, resourcesService, store); - -const routes: Routes = [ - { - path: 'home', - component: HomeLinksComponent, - data: { - auth: [Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER], - title: 'home.home', - breadcrumb: { - menuId: MenuId.home - } - }, - resolve: { - homeDashboard: homeDashboardResolver - } - } -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule] -}) -export class HomeLinksRoutingModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html b/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html deleted file mode 100644 index e30f828629..0000000000 --- a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html +++ /dev/null @@ -1,34 +0,0 @@ - -@if (homeDashboard) { - -} @else { - - @for (section of homeSections$| async; track section) { - - - - {{section.name}} - - - - @for (place of section.places; track place) { - - - {{place.icon}} - {{place.customTranslate ? (place.name | customTranslate) : (place.name | translate)}} - - - } - - - - - } - -} diff --git a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.scss b/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.scss deleted file mode 100644 index 7abd37b40c..0000000000 --- a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.scss +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -@import '../../../../../scss/constants'; - -:host { - width: 100%; - height: 100%; -} - -:host ::ng-deep { - .tb-home-links { - .mat-headline-5 { - font-size: 20px; - @media #{$mat-gt-xmd} { - font-size: 24px; - } - } - .mat-mdc-card { - padding: 0; - margin: 8px; - .mat-mdc-card-title { - margin: 0; - padding: 24px 16px 16px; - } - .mat-mdc-card-title+.mat-mdc-card-content { - padding-top: 0; - } - .mat-mdc-card-content { - padding: 16px; - } - } - .tb-card-button.mat-mdc-outlined-button { - width: 100%; - height: 100%; - max-width: 240px; - display: flex; - flex-direction: column; - align-items: center; - color: rgba(0,0,0,0.76); - .mat-icon { - margin: auto; - } - span.mdc-button__label { - height: 18px; - min-height: 36px; - max-height: 36px; - padding: 0 0 20px 0; - margin: auto; - font-size: 18px; - font-weight: 400; - line-height: 18px; - white-space: normal; - text-align: center; - } - } - } -} - diff --git a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.ts b/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.ts deleted file mode 100644 index c3e26a262f..0000000000 --- a/ui-ngx/src/app/modules/home/pages/home-links/home-links.component.ts +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { - ChangeDetectionStrategy, - ChangeDetectorRef, - Component, - OnInit -} from '@angular/core'; -import { MenuService } from '@core/services/menu.service'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { MediaBreakpoints } from '@shared/models/constants'; -import { HomeSection } from '@core/services/menu.models'; -import { ActivatedRoute } from '@angular/router'; -import { HomeDashboard } from '@shared/models/dashboard.models'; - -@Component({ - selector: 'tb-home-links', - templateUrl: './home-links.component.html', - styleUrls: ['./home-links.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class HomeLinksComponent implements OnInit { - - homeSections$ = this.menuService.homeSections(); - - cols = 2; - - homeDashboard: HomeDashboard = this.route.snapshot.data.homeDashboard; - - hideMainToolbar = true; - - constructor(private menuService: MenuService, - public breakpointObserver: BreakpointObserver, - private cd: ChangeDetectorRef, - private route: ActivatedRoute) { - } - - ngOnInit() { - this.hideMainToolbar = (!!this.homeDashboard && !this.homeDashboard.isSystemDashboard); - if (!this.homeDashboard) { - this.updateColumnCount(); - this.breakpointObserver - .observe([MediaBreakpoints.lg, MediaBreakpoints['gt-lg']]) - .subscribe((state: BreakpointState) => this.updateColumnCount()); - } - } - - private updateColumnCount() { - this.cols = 2; - if (this.breakpointObserver.isMatched(MediaBreakpoints.lg)) { - this.cols = 3; - } - if (this.breakpointObserver.isMatched(MediaBreakpoints['gt-lg'])) { - this.cols = 4; - } - this.cd.detectChanges(); - } - - sectionColspan(section: HomeSection): number { - if (this.breakpointObserver.isMatched(MediaBreakpoints['gt-sm'])) { - let colspan = this.cols; - if (section && section.places && section.places.length <= colspan) { - colspan = section.places.length; - } - return colspan; - } else { - return 2; - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/home-links/home-links.module.ts b/ui-ngx/src/app/modules/home/pages/home-links/home-links.module.ts deleted file mode 100644 index 674fc5bfa8..0000000000 --- a/ui-ngx/src/app/modules/home/pages/home-links/home-links.module.ts +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; - -import { HomeLinksRoutingModule } from './home-links-routing.module'; -import { HomeLinksComponent } from './home-links.component'; -import { SharedModule } from '@app/shared/shared.module'; -import { HomeComponentsModule } from '@home/components/home-components.module'; - -@NgModule({ - declarations: - [ - HomeLinksComponent - ], - imports: [ - CommonModule, - SharedModule, - HomeComponentsModule, - HomeLinksRoutingModule - ] -}) -export class HomeLinksModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss new file mode 100644 index 0000000000..71d9071d98 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-home-table { + width: 100%; + border-collapse: collapse; + + th { + height: 32px; + padding: 0 12px 0 0; + border-bottom: 1px solid var(--tb-line, rgba(0, 0, 0, 0.12)); + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.25px; + text-align: left; + white-space: nowrap; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + .th-label { + display: inline-flex; + align-items: center; + gap: 4px; + margin: 0; + padding: 0; + border: 0; + background: none; + font: inherit; + letter-spacing: inherit; + color: inherit; + cursor: pointer; + user-select: none; + + &:hover { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .tb-sort-icon { + opacity: .6; + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 2px; + } + } + + .tb-sort-icon { + width: 16px; + height: 16px; + font-size: 16px; + opacity: 0; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + transition: opacity .15s ease; + } + + th.sorted .tb-sort-icon { + opacity: 1; + } + + td { + height: 36px; + padding: 0 12px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + vertical-align: middle; + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + tbody tr { + cursor: pointer; + + &:last-child td { + border-bottom: none; + } + + &:hover td { + background: rgba(0, 0, 0, 0.02); + } + } + + .col-time { + text-align: right; + } + + td.col-time { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + th.col-time .th-label { + flex-direction: row-reverse; + } +} + +.tb-home-cell-link { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration: underline; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/_home-tiles.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-tiles.scss new file mode 100644 index 0000000000..048c5c2e90 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-tiles.scss @@ -0,0 +1,281 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-home-tiles { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.tb-home-tile { + --tb-sel: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + position: relative; + display: flex; + flex: 0 0 auto; + flex-direction: column; + justify-content: space-evenly; + box-sizing: border-box; + width: 104px; + min-width: 0; + margin: 0; + padding: 5px 10px; + border: 1px solid rgba(0, 0, 0, 0.10); + border-radius: var(--tb-tile-radius, 10px); + background: #fff; + text-align: left; + color: inherit; + cursor: pointer; + transition: border-color .15s ease, background-color .15s ease; + + &:hover { + border-color: rgba(0, 0, 0, 0.22); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + &[aria-pressed="true"], &[aria-pressed="true"]:hover { + padding-left: 8px; + border-color: transparent; + border-left: 3px solid var(--tb-sel); + border-radius: 0 var(--tb-tile-radius, 10px) var(--tb-tile-radius, 10px) 0; + background: color-mix(in srgb, var(--tb-sel) 6%, #fff); + + .tb-home-tile-label { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + } + + &.can-reset { + .tb-home-tile-label { + padding-right: 16px; + } + + &::after { + content: 'close'; + position: absolute; + top: 4px; + right: 4px; + width: 20px; + height: 20px; + border-radius: 50%; + font-family: 'Material Icons'; + font-size: 16px; + line-height: 20px; + text-align: center; + font-feature-settings: 'liga'; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + &:hover::after { + background: #fff; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + } + + &.zero { + .tb-home-tile-count { + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &:disabled { + cursor: default; + + &:hover { + border-color: rgba(0, 0, 0, 0.10); + } + } + } +} + +.tb-home-tile-label { + overflow: hidden; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.1px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-home-tile-count { + display: flex; + align-items: center; + gap: 6px; + font: 500 20px/28px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-home-all-clear { + display: flex; + align-items: center; + gap: 12px; + padding: 2px 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-home-all-clear-glyph { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 50%; + background: var(--tb-ok-tint, rgba(25, 128, 56, 0.08)); + color: var(--tb-ok, #198038); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: inherit; + } +} + +.tb-home-empty-note { + padding: 4px 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +@container (max-width: 459px) { + .tb-home-tile { + flex: 1 1 88px; + width: auto; + max-width: 140px; + padding-left: 8px; + padding-right: 8px; + } + + .tb-home-tile-label { + letter-spacing: 0; + } +} + +.tb-home-setup-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + padding: 8px 16px 12px; + text-align: center; +} + +.tb-home-setup-empty-glyph { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + border-radius: 50%; + background: color-mix(in srgb, var(--tb-primary-500) 10%, transparent); + color: var(--tb-primary-500); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: inherit; + } +} + +.tb-home-setup-empty-text { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; + + p { + max-width: 36em; + margin: 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } +} + +.tb-home-setup-empty-title { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-home-setup-empty-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 4px 16px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + + a { + border-radius: 4px; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + color: var(--tb-primary-500); + transition: text-decoration-color .15s ease; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration-color: currentColor; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + } +} + +.tb-home-ext { + width: 14px; + height: 14px; + margin-left: 2px; + font-size: 14px; + line-height: 14px; + vertical-align: -2px; + opacity: .7; +} + +.tb-home-add.mat-mdc-button { + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + .mat-icon { + margin-right: 6px; + } +} + +@container (max-width: 459px) { + .tb-home-add.mat-mdc-button { + min-width: 40px; + padding: 0 8px; + + .mat-icon { + margin: 0; + } + + .tb-home-add-label { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.scss new file mode 100644 index 0000000000..6bb633911f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.scss @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-ai-compose-row { + display: flex; + align-items: flex-start; + gap: 8px; + min-width: 0; + max-width: var(--tb-home-compose-width, 760px); + container-type: inline-size; +} + +.tb-ai-home-composer { + flex: 1 1 auto; + min-width: 0; +} + +.tb-ai-chats-btn { + &:hover, &:focus, &:active { + border-bottom: none; + } + + flex: none; + display: inline-flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + height: 50px; + max-width: 160px; + padding: 0 12px 0 16px; + overflow: hidden; + white-space: nowrap; + border-radius: 12px; + background: transparent; + box-shadow: inset 0 0 0 1px var(--tb-line, rgba(0, 0, 0, 0.12)); + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + text-decoration: none; + border-bottom: none; + mix-blend-mode: multiply; + transition: max-width .2s ease, padding .2s ease, margin .2s ease, opacity .15s ease, background-color .15s, color .15s; + + .mat-icon { + flex: none; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } + + .tb-ai-chats-go { + margin-left: -4px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + &:hover { + background: var(--tb-line-soft, rgba(0, 0, 0, 0.05)); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + .mat-icon { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } +} + +.tb-ai-compose-row.open .tb-ai-chats-btn { + max-width: 0; + margin-left: -8px; + padding: 0; + opacity: 0; + visibility: hidden; + transition: max-width .2s ease, padding .2s ease, margin .2s ease, opacity .1s ease, visibility 0s .2s; +} + +@container (max-width: 480px) { + .tb-ai-chats-btn { + width: 50px; + padding: 0; + justify-content: center; + + .tb-ai-chats-t, .tb-ai-chats-go { + display: none; + } + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-ai-chats-btn { + transition: none; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts new file mode 100644 index 0000000000..553a937a98 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts @@ -0,0 +1,144 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + Renderer2, + signal, + untracked, + ViewChild, + ViewContainerRef +} from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentUserSettings } from '@core/auth/auth.selectors'; +import { ActionPreferencesUpdateAiTour } from '@core/auth/auth.actions'; +import { AiTourStep } from '@shared/models/user-settings.models'; +import { TourService } from '@core/services/tour.service'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { escapeTourText, TourPopupRef, TourPopupService } from '@shared/components/tour/tour-popup.service'; +import { Router } from '@angular/router'; +import { MatDialog } from '@angular/material/dialog'; +import { TranslateService } from '@ngx-translate/core'; +import { AiPromptMessage } from '@shared/models/ai-chat.models'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; + +const OFFER_DELAY_MS = 900; + +@Component({ + selector: 'tb-ai-assistant-home', + template: ` + + `, + styleUrls: ['./ai-assistant-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiAssistantHomeComponent implements AfterViewInit { + + @ViewChild(AiPromptInputComponent) composer: AiPromptInputComponent; + + @ViewChild(AiPromptInputComponent, {read: ElementRef}) composerHost: ElementRef; + + readonly composerFocused = signal(false); + + private router = inject(Router); + private panelService = inject(AiAssistantPanelService); + private dialog = inject(MatDialog); + private translate = inject(TranslateService); + private store = inject(Store); + private tourService = inject(TourService); + private chats = inject(AiChatsService); + private solutions = inject(AiSolutionsService); + + readonly hasChats = computed(() => !this.chats.loaded() || !this.solutions.loaded() + || this.chats.chats().length > 0 || this.solutions.solutions().length > 0); + private tourPopup = inject(TourPopupService); + private renderer = inject(Renderer2); + private viewContainerRef = inject(ViewContainerRef); + + private offer: TourPopupRef | null = null; + private offerTimer: ReturnType | null = null; + + constructor() { + this.chats.ensureLoaded(); + this.solutions.ensureLoaded(); + inject(DestroyRef).onDestroy(() => { + clearTimeout(this.offerTimer); + this.offer?.close(); + }); + } + + ngAfterViewInit(): void { + if (this.tourService.aiAvailable() && this.seen(AiTourStep.WELCOME) && !this.seen(AiTourStep.HOME)) { + this.chats.watchStatus(); + this.offerTimer = setTimeout(() => this.showOffer(), OFFER_DELAY_MS); + } + } + + private showOffer(): void { + this.offerTimer = null; + const host = this.composerHost?.nativeElement; + const target = host?.querySelector('.tb-ai-composer') ?? host; + if (!target || this.seen(AiTourStep.HOME) || this.tourService.active() || this.dialog.openDialogs.length + || untracked(this.chats.statusChats).some(chat => this.chats.levelOf(chat) === 'running')) { + return; + } + const keyboard = matchMedia('(hover: hover) and (pointer: fine)').matches; + this.offer = this.tourPopup.show({ + target, + hostView: this.viewContainerRef, + renderer: this.renderer, + placement: ['bottom', 'top'], + hint: true, + title: this.translate.instant('home.ai.offer-title'), + text: escapeTourText(this.translate.instant('home.ai.offer-text')), + foot: keyboard ? escapeTourText(this.translate.instant('home.ai.offer-key', {key: '\u0000'})).replace('\u0000', '/') : null, + nextLabel: this.translate.instant('home.ai.offer-action'), + onNext: () => this.closeOffer(true), + onClose: () => this.closeOffer(false), + onEscape: () => this.closeOffer(false), + onHidden: () => this.offer = null + }); + } + + private closeOffer(ask: boolean): void { + const offer = this.offer; + this.offer = null; + offer?.close(); + if (!this.seen(AiTourStep.HOME)) { + this.store.dispatch(new ActionPreferencesUpdateAiTour({step: AiTourStep.HOME, seen: true})); + } + if (ask) { + this.composer?.focus(); + } + } + + private seen(step: AiTourStep): boolean { + return !!getCurrentUserSettings(this.store)?.aiTour?.[step]; + } + + send(prompt: AiPromptMessage): void { + this.panelService.handOff(prompt); + this.router.navigateByUrl('/ai-assistant'); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.scss new file mode 100644 index 0000000000..03e24926c1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.scss @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-ai-start-block { + margin-top: 22px; + container-type: inline-size; +} + +.tb-ai-start-block.appear { + animation: tb-ai-start-in .25s ease-out; +} + +@keyframes tb-ai-start-in { + from { + opacity: 0; + } +} + +.tb-ai-start-block.reserve .tb-ai-start-h { + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.tb-ai-start.placeholder { + pointer-events: none; +} + +.tb-ai-start-skeleton { + background: linear-gradient(90deg, rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.09) 50%, rgba(0, 0, 0, 0.05) 100%) 0 0 / 200% 100%; + animation: tb-ai-start-shimmer 1.4s ease-in-out infinite; +} + +.tb-ai-start-line { + width: 55%; + height: 12px; + border-radius: 4px; +} + +@keyframes tb-ai-start-shimmer { + from { + background-position: 100% 0; + } + to { + background-position: -100% 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-ai-start-block.appear, .tb-ai-start-skeleton { + animation: none; + } +} + +.tb-ai-start-h { + margin: 0 2px 6px; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: .1px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-ai-starts { + display: flex; + align-items: stretch; + gap: 8px; + max-width: var(--tb-home-compose-width, 760px); +} + +.tb-ai-start { + display: flex; + flex: 1 1 0; + align-items: center; + gap: 12px; + box-sizing: border-box; + min-width: 0; + min-height: 56px; + padding: 10px; + border-radius: 12px; + background: #fff; + 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)); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + transition: box-shadow .15s ease; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + 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)), 0 4px 12px -4px rgba(20, 52, 58, 0.14); + + .tb-ai-start-go { + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus, #00897b); + outline-offset: 2px; + } +} + +.tb-ai-start-ic { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 10px; + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: inherit; + } +} + +.tb-ai-start.dev .tb-ai-start-ic { + color: var(--entity-device-fg, #535eb8); + box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--entity-device-fg, #535eb8) 8%, transparent); + background: radial-gradient(70% 70% at 18% 14%, rgba(255, 255, 255, 0.55), transparent 65%), + linear-gradient(135deg in oklab, color-mix(in oklab, var(--ai-light-aqua) 70%, var(--entity-device-bg, #e9efff)) 0%, + var(--entity-device-bg, #e9efff) 48%, color-mix(in oklab, var(--entity-device-fg, #535eb8) 30%, var(--entity-device-bg, #e9efff)) 100%); +} + +.tb-ai-start.ex .tb-ai-start-ic { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--ai-teal-600, #00897b) 10%, transparent); + background: radial-gradient(70% 70% at 18% 14%, rgba(255, 255, 255, 0.5), transparent 65%), + linear-gradient(135deg in oklab, var(--ai-dark-accent-pale, #c4f3ea), var(--ai-light-teal)); +} + +.tb-ai-start.cli .tb-ai-start-ic { + color: var(--ai-dark-accent, #8fe3d3); + box-shadow: 0 2px 6px color-mix(in oklab, var(--tb-ink, rgba(0, 0, 0, 0.87)) 18%, transparent); + background: radial-gradient(80% 80% at 16% 10%, color-mix(in oklab, var(--ai-dark-accent-soft, #80d6c8) 18%, transparent), transparent 62%), + linear-gradient(160deg in oklab, var(--ai-dark, #24323b), color-mix(in oklab, var(--ai-dark, #24323b) 72%, var(--tb-ink, rgba(0, 0, 0, 0.87)))); +} + +.tb-ai-start-t { + display: -webkit-box; + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + line-clamp: 2; +} + +.tb-ai-start-go { + flex: none; + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + transition: color .15s ease, transform .15s ease; +} + +@container (max-width: 560px) { + .tb-ai-starts { + flex-direction: column; + } + + .tb-ai-start { + flex: none; + width: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-ai-start-go { + transition: none; + } + + .tb-ai-start:hover .tb-ai-start-go { + transform: none; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts new file mode 100644 index 0000000000..a0a6f62812 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { EntityType } from '@shared/models/entity-type.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { NEW_SOLUTION_ID } from '@shared/models/solution-creator.models'; + +@Component({ + selector: 'tb-ai-start-home', + template: ` + @if (!resolved()) { + @if (reserved) { + + } + } @else if (show()) { + + } + `, + styleUrls: ['./ai-start-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiStartHomeComponent { + + readonly newSolutionId = NEW_SOLUTION_ID; + + private chats = inject(AiChatsService); + private solutions = inject(AiSolutionsService); + + private readonly devices = signal(null); + + readonly resolved = computed(() => this.chats.loaded() && this.solutions.loaded() && this.devices() !== null); + + readonly show = computed(() => this.resolved() && this.devices() === 0 + && !this.chats.chats().length && !this.solutions.solutions().length); + + private readonly shownKey = `tb-home-ai-start:${getCurrentAuthUser(inject(Store))?.userId}`; + + readonly reserved = this.readShown(); + + constructor() { + this.chats.ensureLoaded(); + this.solutions.ensureLoaded(); + inject(HomeCountService).watchEntityCount(EntityType.DEVICE, count => this.devices.set(count), inject(DestroyRef)); + effect(() => { + if (this.resolved()) { + this.writeShown(this.show()); + } + }); + } + + private readShown(): boolean { + return readStored(this.shownKey) === '1'; + } + + private writeShown(shown: boolean): void { + writeStored(this.shownKey, shown ? '1' : '0'); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html new file mode 100644 index 0000000000..bd9aec8262 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html @@ -0,0 +1,190 @@ + + + + @if (total()) { + + } + @if (canAddRule) { + + } + + @if (emptyState() === 'rules') { + + } @else if (emptyState() === 'devices') { +
+ +
{{ 'home.alarms.no-alarms-yet' | translate }}
+
+ } @else if (emptyState() === 'clear') { +
+ + {{ 'home.alarms.none-active' | translate }} {{ 'home.alarms.view-cleared' | translate }} +
+ } @else if (total()) { +
+ @for (tile of tiles(); track tile.severity) { + + } +
+ @if (rows().length) { + + + + + + + + @if (!mine()) { + + } + + + + + + @for (row of rows(); track row.alarm.id.id) { + + + + + + @if (!mine()) { + + } + + + + } + +
+ + {{ 'home.alarms.type' | translate }}{{ 'home.alarms.originator' | translate }} + + {{ 'home.alarms.assignee' | translate }}{{ 'home.alarms.ack' | translate }}
+ + + {{ severityLabel(row.alarm.severity) | translate }} + + + + {{ row.alarm.type }} + + + @if (row.originatorLink) { + {{ row.alarm.originatorDisplayName || row.alarm.originatorName }} + } @else { + {{ row.alarm.originatorDisplayName || row.alarm.originatorName }} + } + · {{ row.ago }} + + + @if (row.originatorLink) { + {{ row.alarm.originatorDisplayName || row.alarm.originatorName }} + } @else { + {{ row.alarm.originatorDisplayName || row.alarm.originatorName }} + } + {{ row.ago }} + @if (row.assigneeName) { + {{ row.initials }} + } @else { + + — + @if (canWrite) { + + } + + } + + @if (row.alarm.acknowledged) { + check_circle + } @else if (canWrite) { + + } @else { + radio_button_unchecked + } + + +
+ } @else if (alarmsLoaded()) { +
{{ emptyNote().key | translate: emptyNote().params }}
+ } + + } +
+ + + + @if (canWrite) { + + } + @if (canWrite && !row.mine) { + + } + + @if (canWrite) { + + } + + diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.scss new file mode 100644 index 0000000000..c48a7487d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.scss @@ -0,0 +1,282 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; +@use './home-table'; + +:host { + display: block; + min-width: 0; + container: tb-alarms-home / inline-size; +} + +.tb-alarms-clear-link, .tb-alarms-link { + &, &:hover, &:focus, &:active { + border-bottom: none; + } +} + +.tb-alarms-clear-link { + font-weight: 500; + color: var(--tb-primary-500); +} + +.tb-home-tile { + &.critical { --tb-sel: var(--tb-sev-critical, #D12730); } + &.major { --tb-sel: var(--tb-sev-major, #F35E09); } + &.minor { --tb-sel: var(--tb-sev-minor, #B47604); } + &.warning { --tb-sel: var(--tb-sev-warning, #B47604); } +} + +.tb-alarms-tile-mark ::ng-deep svg { + width: 20px; + height: 20px; +} + +.tb-alarms-table { + tbody tr:is(:hover, :focus-within) .tb-alarms-assign { + visibility: visible; + } + + td.col-type .tb-alarms-cell-main { + display: flex; + min-width: 0; + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + } + + td.col-origin { + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .col-assignee, .col-ack { + width: 1%; + padding-left: 8px; + padding-right: 8px; + text-align: center; + } + + .col-actions { + width: 32px; + padding-right: 0; + text-align: right; + } +} + +.tb-alarms-sev { + display: inline-flex; + align-items: center; + gap: 8px; + white-space: nowrap; +} + +.tb-alarms-link { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} + +.tb-alarms-origin { + color: inherit; +} + +.tb-alarms-cell-sub { + display: none; + overflow: hidden; + font-size: 12px; + line-height: 16px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .tb-alarms-origin { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + &:hover { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + } +} + +.tb-alarms-assignee { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.06); + font: 500 10px/1 var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + vertical-align: middle; + + &.me { + background: var(--tb-primary-500); + color: var(--tb-primary-contrast-500, #fff); + } +} + +.tb-alarms-assign-cell { + display: inline-grid; + place-items: center; + vertical-align: middle; + + > * { + grid-area: 1 / 1; + } +} + +.tb-alarms-dash { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} + +.tb-alarms-assign.mat-mdc-icon-button, .tb-alarms-ack.mat-mdc-icon-button, .tb-alarms-menu.mat-mdc-icon-button { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + margin: -6px 0; + padding: 0; + vertical-align: middle; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } + + .mat-mdc-button-touch-target { + width: 32px; + height: 32px; + } + + &:is(:hover, :focus-visible) { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } +} + +.tb-alarms-assign.mat-mdc-icon-button { + visibility: hidden; + background: var(--tb-surface, #fff); +} + +.tb-alarms-ack.mat-mdc-icon-button { + .on { + display: none; + } + + &:is(:hover, :focus-visible) { + .off { + display: none; + } + + .on { + display: inline-block; + } + } +} + +.tb-alarms-acked, .tb-alarms-unacked { + width: 20px; + height: 20px; + font-size: 20px; + vertical-align: middle; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-alarms-unacked { + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +@container tb-alarms-home (max-width: 599px) { + .tb-alarms-table { + .col-origin { + display: none; + } + + td.col-type { + width: 99%; + max-width: 0; + padding-top: 6px; + padding-bottom: 6px; + + .tb-alarms-cell-main { + max-width: none; + } + } + + .col-severity { + width: 1%; + padding-right: 4px; + } + + tbody td.col-severity { + padding-top: 6px; + vertical-align: top; + } + + th.col-severity .th-text { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + } + } + + .tb-alarms-sev { + gap: 0; + height: 20px; + } + + .tb-alarms-sev-word { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + } + + .tb-alarms-cell-sub { + display: block; + } + + .tb-alarms-sub-age { + display: none; + } +} + +@container tb-alarms-home (max-width: 459px) { + .tb-alarms-table { + .col-age { + display: none; + } + + th.col-assignee .th-text { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + } + } + + .tb-alarms-sub-age { + display: inline; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts new file mode 100644 index 0000000000..a023778112 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts @@ -0,0 +1,414 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + inject, + NgZone, + signal, + untracked, + WritableSignal +} from '@angular/core'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { MatDialog } from '@angular/material/dialog'; +import { TranslateService } from '@ngx-translate/core'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { AlarmService } from '@core/http/alarm.service'; +import { DialogService } from '@core/services/dialog.service'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { AlarmCountCmd, AlarmDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AlarmRulesService } from '@core/http/alarm-rules.service'; +import { PageLink } from '@shared/models/page/page-link'; +import { HelpLinks } from '@shared/models/constants'; +import { catchError, of } from 'rxjs'; +import { AlarmData, AlarmDataPageLink, EntityKeyType } from '@shared/models/query/query.models'; +import { Direction } from '@shared/models/page/sort-order'; +import { AlarmSearchStatus, AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType } from '@shared/models/entity-type.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { AlarmDetailsDialogComponent, AlarmDetailsDialogData } from '@home/components/alarm/alarm-details-dialog.component'; +import { homeAgo, homeListPageSize, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { MINUTE } from '@shared/models/time/time.models'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; + +const MINE_KEY = 'tb-home-alarms-mine'; +const SEVERITIES = [AlarmSeverity.CRITICAL, AlarmSeverity.MAJOR, AlarmSeverity.MINOR, AlarmSeverity.WARNING]; + +type AlarmSortKey = 'severity' | 'createdTime'; + +interface SeverityTile { + severity: AlarmSeverity; + count: number; + pressed: boolean; + hot: boolean; +} + +export interface AlarmHomeRow { + alarm: AlarmData; + ago: string; + originatorLink: string | null; + assigneeName: string | null; + initials: string; + mine: boolean; +} + +const readMine = (): boolean => { + return readStored(MINE_KEY) === '1'; +}; + +const writeMine = (mine: boolean): void => { + writeStored(MINE_KEY, mine ? '1' : null); +}; + +@Component({ + selector: 'tb-alarms-home', + templateUrl: './alarms-home.component.html', + styleUrls: ['./alarms-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AlarmsHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.ALARMS]; + + readonly whoseOptions: HomeToggleOption[] = [ + {value: false, label: 'home.alarms.all'}, + {value: true, label: 'home.alarms.mine'} + ]; + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private store = inject(Store); + private router = inject(Router); + private dialog = inject(MatDialog); + private dialogService = inject(DialogService); + private alarmService = inject(AlarmService); + private toast = inject(ToastNotificationService); + private translate = inject(TranslateService); + private alarmRulesService = inject(AlarmRulesService); + private permissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); + + private readonly authUser = getCurrentAuthUser(this.store); + private readonly userId = this.authUser?.userId; + readonly tenantAdmin = this.authUser?.authority === Authority.TENANT_ADMIN; + readonly canWrite = this.permissions.canWriteAlarms(); + readonly canAddRule = this.permissions.canAddAlarmRules(); + private readonly canReadRules = this.permissions.canReadAlarmRules(); + private readonly canReadDevices = this.permissions.canReadEntities(EntityType.DEVICE); + + readonly mine = signal(readMine()); + readonly severity = signal(null); + readonly expanded = signal(false); + readonly sortKey = signal('severity'); + readonly sortDesc = signal(true); + + readonly total = signal(null); + readonly hasRules = signal(null); + readonly devices = signal(null); + readonly howToLink = HelpLinks.linksMap.alarmRules; + + readonly emptyState = computed<'rules' | 'devices' | 'clear' | null>(() => { + if (this.total() !== 0 || this.hasRules() === null || this.devices() === null) { + return null; + } + if (this.canReadRules && !this.hasRules()) { + return 'rules'; + } + return this.devices() ? 'clear' : 'devices'; + }); + + private readonly severityCounts = new Map>( + SEVERITIES.map(severity => [severity, signal(null)]) + ); + + private readonly alarms = signal(null); + readonly listed = signal(0); + readonly alarmsLoaded = computed(() => this.alarms() !== null); + private readonly now = signal(Date.now()); + + private totalSubscriber: TelemetrySubscriber | null = null; + private severitySubscribers: TelemetrySubscriber[] = []; + private dataSubscriber: TelemetrySubscriber | null = null; + + readonly tiles = computed(() => { + const pressed = this.severity(); + return SEVERITIES.map(severity => { + const count = this.severityCounts.get(severity)() ?? 0; + return {severity, count, pressed: pressed === severity, hot: severity === AlarmSeverity.CRITICAL && count > 0}; + }).filter(tile => tile.severity === AlarmSeverity.CRITICAL || tile.count > 0 || tile.pressed); + }); + + readonly rows = computed(() => { + const now = this.now(); + return (this.alarms() ?? []).slice(0, homeListShown(this.listed(), this.expanded())).map(alarm => this.toRow(alarm, now)); + }); + + readonly emptyNote = computed<{key: string; params: Record}>(() => { + const severity = this.severity(); + const mine = this.mine(); + if (severity) { + return { + key: mine ? 'home.alarms.none-severity-mine' : 'home.alarms.none-severity', + params: {severity: this.translate.instant(alarmSeverityTranslations.get(severity)).toLowerCase()} + }; + } + return {key: mine ? 'home.alarms.none-mine' : 'home.alarms.none-active', params: {}}; + }); + + readonly viewAllParams = computed>(() => { + const severity = this.severity(); + return { + ...(severity ? {severityList: [severity]} : {}), + ...(this.mine() ? {assignedToMe: true} : {}) + }; + }); + + private readonly pageLink = computed(() => { + const severity = this.severity(); + const key = this.sortKey(); + const desc = this.sortDesc(); + return { + page: 0, + pageSize: homeListPageSize(this.expanded()), + sortOrder: { + key: {type: EntityKeyType.ALARM_FIELD, key}, + direction: key === 'severity' ? (desc ? Direction.ASC : Direction.DESC) : (desc ? Direction.DESC : Direction.ASC) + }, + statusList: [AlarmSearchStatus.ACTIVE], + ...(severity ? {severityList: [severity]} : {}), + ...(this.mine() && this.userId ? {assigneeId: {entityType: EntityType.USER, id: this.userId}} : {}) + }; + }); + + constructor() { + this.totalSubscriber = this.subscribeCount(this.total); + if (this.canReadDevices) { + this.homeCounts.watchEntityCount(EntityType.DEVICE, count => this.devices.set(count), this.destroyRef); + } else { + this.devices.set(1); + } + if (this.canReadRules) { + this.alarmRulesService.getAlarmRules(new PageLink(1), undefined, {ignoreLoading: true}).pipe( + catchError(() => of(null)) + ).subscribe(page => this.hasRules.set(!page || page.totalElements > 0)); + } else { + this.hasRules.set(true); + } + effect(() => { + const mine = this.mine(); + untracked(() => this.subscribeSeverityCounts(mine)); + }); + effect(() => { + const pageLink = this.pageLink(); + untracked(() => this.subscribeAlarms(pageLink)); + }); + const tick = setInterval(() => this.now.set(Date.now()), MINUTE); + this.destroyRef.onDestroy(() => { + clearInterval(tick); + this.totalSubscriber?.unsubscribe(); + this.severitySubscribers.forEach(subscriber => subscriber.unsubscribe()); + this.dataSubscriber?.unsubscribe(); + }); + } + + severityLabel(severity: AlarmSeverity | string): string { + return alarmSeverityTranslations.get(severity as AlarmSeverity) ?? String(severity); + } + + setMine(mine: boolean): void { + if (mine !== this.mine()) { + this.mine.set(mine); + writeMine(mine); + } + } + + pick(tile: SeverityTile): void { + if (tile.count || tile.pressed) { + this.severity.set(tile.pressed ? null : tile.severity); + } + } + + sortBy(key: AlarmSortKey): void { + if (this.sortKey() === key) { + this.sortDesc.set(!this.sortDesc()); + } else { + this.sortKey.set(key); + this.sortDesc.set(true); + } + } + + ariaSort(key: AlarmSortKey): string { + if (this.sortKey() !== key) { + return 'none'; + } + return this.sortDesc() ? 'descending' : 'ascending'; + } + + addAlarmRule(): void { + this.router.navigate(['/alarms/alarm-rules'], {queryParams: {action: 'add'}}); + } + + openDetails(row: AlarmHomeRow, $event?: Event): void { + $event?.preventDefault(); + $event?.stopPropagation(); + this.dialog.open(AlarmDetailsDialogComponent, { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + alarmId: row.alarm.id.id, + alarm: row.alarm, + allowAcknowledgment: this.canWrite, + allowClear: this.canWrite, + displayDetails: true, + allowAssign: this.canWrite + } + }).afterClosed().subscribe(changed => { + if (changed) { + this.refresh(); + } + }); + } + + stop($event: Event): void { + $event.stopPropagation(); + } + + acknowledge(row: AlarmHomeRow, $event?: Event): void { + $event?.stopPropagation(); + if (row.alarm.acknowledged) { + return; + } + this.patch(row.alarm.id.id, {acknowledged: true}); + this.alarmService.ackAlarm(row.alarm.id.id).subscribe({ + next: () => { + this.notify('home.alarms.acknowledged', row); + this.refresh(); + }, + error: () => this.refresh() + }); + } + + assignToMe(row: AlarmHomeRow, $event?: Event): void { + $event?.stopPropagation(); + if (this.userId) { + this.alarmService.assignAlarm(row.alarm.id.id, this.userId).subscribe(() => { + this.notify('home.alarms.assigned', row); + this.refresh(); + }); + } + } + + clear(row: AlarmHomeRow): void { + const name = this.alarmName(row); + this.dialogService.confirm( + this.translate.instant('home.alarms.clear-title', {name}), + this.translate.instant('home.alarms.clear-text'), + this.translate.instant('action.cancel'), + this.translate.instant('home.alarms.clear') + ).subscribe(confirmed => { + if (confirmed) { + this.alarmService.clearAlarm(row.alarm.id.id).subscribe(() => { + this.notify('home.alarms.cleared', row); + this.refresh(); + }); + } + }); + } + + private subscribeAlarms(pageLink: AlarmDataPageLink): void { + this.dataSubscriber?.unsubscribe(); + const cmd = new AlarmDataCmd(); + cmd.query = { + entityFilter: null, + pageLink, + alarmFields: [], + entityFields: [], + latestValues: [] + }; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + this.dataSubscriber = subscriber; + subscriber.alarmData$.subscribe(update => { + if (update.data) { + this.listed.set(update.data.totalElements); + this.alarms.set(update.data.data); + } else if (update.update) { + const byId = new Map(update.update.map(alarm => [alarm.id.id, alarm])); + this.alarms.set((this.alarms() ?? []).map(alarm => byId.get(alarm.id.id) ?? alarm)); + } + }); + subscriber.subscribe(); + } + + private subscribeSeverityCounts(mine: boolean): void { + this.severitySubscribers.forEach(subscriber => subscriber.unsubscribe()); + this.severitySubscribers = SEVERITIES.map(severity => this.subscribeCount(this.severityCounts.get(severity), severity, mine)); + } + + private subscribeCount(target: WritableSignal, severity?: AlarmSeverity, mine = false): TelemetrySubscriber { + const cmd = new AlarmCountCmd(); + cmd.query = { + entityFilter: null, + statusList: [AlarmSearchStatus.ACTIVE], + ...(severity ? {severityList: [severity]} : {}), + ...(mine && this.userId ? {assigneeId: {entityType: EntityType.USER, id: this.userId}} : {}) + }; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.alarmCount$.subscribe(update => target.set(update.count ?? 0)); + subscriber.subscribe(); + return subscriber; + } + + private refresh(): void { + this.subscribeAlarms(this.pageLink()); + this.totalSubscriber?.unsubscribe(); + this.totalSubscriber = this.subscribeCount(this.total); + this.subscribeSeverityCounts(this.mine()); + } + + private patch(alarmId: string, change: Partial): void { + const alarms = this.alarms(); + if (alarms) { + this.alarms.set(alarms.map(alarm => alarm.id.id === alarmId ? {...alarm, ...change} : alarm)); + } + } + + private notify(key: string, row: AlarmHomeRow): void { + this.toast.dispatchNotification(homeToast(this.translate.instant(key, {name: this.alarmName(row)}))); + } + + private alarmName(row: AlarmHomeRow): string { + return this.translate.instant('home.alarms.name', {type: row.alarm.type, originator: row.alarm.originatorName ?? ''}); + } + + private toRow(alarm: AlarmData, now: number): AlarmHomeRow { + const assignee = alarm.assigneeId ? alarm.assignee : null; + const assigneeName = assignee ? [assignee.firstName, assignee.lastName].filter(Boolean).join(' ') || assignee.email : null; + const initials = assignee + ? (assignee.firstName && assignee.lastName ? assignee.firstName[0] + assignee.lastName[0] : (assigneeName ?? '').slice(0, 2)).toUpperCase() + : ''; + const originator = alarm.originator; + return { + alarm, + ago: homeAgo(this.translate, now - (alarm.createdTime ?? now)), + originatorLink: originator ? this.permissions.entityDetailsLink(originator.entityType as EntityType, originator.id) : null, + assigneeName, + initials, + mine: !!alarm.assigneeId && alarm.assigneeId.id === this.userId + }; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.html new file mode 100644 index 0000000000..c76a9c4718 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.html @@ -0,0 +1,35 @@ + + + + @if (groups().length) { + + } + + @if (groups().length) { +
+ @for (group of groups(); track group.id) { +
+
{{ group.label | translate }}
+
+ @for (row of group.rows; track row.name) { +
{{ row.name | translate }}
+
+ {{ row.used | shortNumber: {roundDown: true} }} / {{ row.limit ? (row.limit | shortNumber: {roundDown: true}) : '∞' }} +
+
+ +
+ } +
+
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.scss new file mode 100644 index 0000000000..6c6844c849 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.scss @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; + container: tb-usage-home / inline-size; +} + +.tb-usage-group-label { + display: none; + align-self: flex-start; + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.25px; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} + +.tb-usage-groups { + display: grid; +} + +.tb-usage-group { + grid-area: 1 / 1; + align-self: start; + container-type: inline-size; +} + +.tb-usage-groups[data-tab="entities"] > [data-group="api"], .tb-usage-groups[data-tab="api"] > [data-group="entities"] { + visibility: hidden; +} + +.tb-usage-list { + display: grid; + grid-template-columns: minmax(max-content, 1fr) max-content minmax(32px, 112px); + column-gap: 10px; + row-gap: 10px; + align-items: center; +} + +@container (max-width: 280px) { + .tb-usage-list { + grid-template-columns: minmax(0, 1fr) max-content 32px; + } +} + +.tb-usage-item { + overflow: hidden; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + &.critical { + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.tb-usage-item-counts { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-align: right; + font-variant-numeric: tabular-nums; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + &.critical { + color: var(--tb-sev-critical, #D12730); + } +} + +.tb-usage-progress { + height: 8px; + overflow: hidden; + border-radius: 2px; + background: rgba(0, 0, 0, 0.08); + + > i { + display: block; + height: 100%; + border-radius: 2px; + background: var(--tb-primary-500); + } + + &.critical { + background: rgba(209, 39, 48, 0.06); + + > i { + background: var(--tb-sev-critical, #D12730); + } + } +} + +@container tb-usage-home (min-width: 560px) { + .tb-usage-tabs { + display: none; + } + + .tb-usage-groups { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px 40px; + } + + .tb-usage-groups[data-tab] > .tb-usage-group { + display: flex; + flex-direction: column; + grid-area: auto; + gap: 10px; + visibility: visible; + } + + .tb-usage-group-label { + display: inline-flex; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.ts new file mode 100644 index 0000000000..38f13c2901 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/api-usage-home.component.ts @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, NgZone, signal } from '@angular/core'; +import { UsageInfoService } from '@core/http/usage-info.service'; +import { TourService } from '@core/services/tour.service'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; +import { UsageInfo } from '@shared/models/usage.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; + +const CRITICAL_PERCENT = 90; + +type UsageGroupId = 'entities' | 'api'; + +interface UsageRow { + name: string; + used: number; + limit: number; + percent: number; + critical: boolean; +} + +interface UsageGroup { + id: UsageGroupId; + label: string; + rows: UsageRow[]; +} + +const ENTITY_ROWS: [string, keyof UsageInfo, keyof UsageInfo][] = [ + ['device.devices', 'devices', 'maxDevices'], + ['asset.assets', 'assets', 'maxAssets'], + ['user.users', 'users', 'maxUsers'], + ['dashboard.dashboards', 'dashboards', 'maxDashboards'], + ['customer.customers', 'customers', 'maxCustomers'] +]; + +const API_ROWS: [string, string, string][] = [ + ['api-usage.transport-messages', 'transportMsgCount', 'transportMsgLimit'], + ['api-usage.javascript', 'jsExecutionCount', 'jsExecutionLimit'], + ['api-usage.alarms-created', 'createdAlarmsCount', 'createdAlarmsLimit'], + ['api-usage.email', 'emailCount', 'emailLimit'], + ['api-usage.sms', 'smsCount', 'smsLimit'], + ['api-usage.ai-credits', 'aiCreditsCount', 'aiCreditsLimit'] +]; + +@Component({ + selector: 'tb-api-usage-home', + templateUrl: './api-usage-home.component.html', + styleUrls: ['./api-usage-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class ApiUsageHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.USAGE]; + + readonly tabOptions: HomeToggleOption[] = [ + {value: 'entities', label: 'widgets.usage-info.entities'}, + {value: 'api', label: 'widgets.usage-info.api-calls'} + ]; + + private readonly apiRows = inject(TourService).aiAvailable() ? API_ROWS : API_ROWS.filter(([name]) => name !== 'api-usage.ai-credits'); + + private readonly apiKeys = this.apiRows.flatMap(([, count, limit]) => [count, limit]); + + private readonly usage = signal(null); + private readonly apiUsage = signal<{[key: string]: number} | null>(null); + private tabChosen = false; + + readonly tab = signal('entities'); + + readonly groups = computed(() => { + const usage = this.usage(); + const apiUsage = this.apiUsage(); + if (!usage || !apiUsage) { + return []; + } + return [ + { + id: 'entities', + label: 'widgets.usage-info.entities', + rows: ENTITY_ROWS.map(([name, used, limit]) => this.toRow(name, usage[used] as number, usage[limit] as number)) + }, + { + id: 'api', + label: 'widgets.usage-info.api-calls', + rows: this.apiRows.map(([name, count, limit]) => this.toRow(name, apiUsage[count], apiUsage[limit])) + } + ]; + }); + + constructor() { + inject(UsageInfoService).getUsageInfo().subscribe(usage => { + this.usage.set(usage); + this.chooseTab(); + }); + const subscriber = this.subscribeApiUsage(inject(TelemetryWebsocketService), inject(NgZone)); + inject(DestroyRef).onDestroy(() => subscriber.unsubscribe()); + } + + private subscribeApiUsage(telemetryWsService: TelemetryWebsocketService, zone: NgZone): TelemetrySubscriber { + const keys = this.apiKeys.map(key => ({type: EntityKeyType.TIME_SERIES, key})); + const cmd = new EntityDataCmd(); + cmd.query = { + entityFilter: {type: AliasFilterType.apiUsageState}, + pageLink: {page: 0, pageSize: 1}, + entityFields: [], + latestValues: keys + }; + cmd.latestCmd = {keys}; + const subscriber = new TelemetrySubscriber(telemetryWsService, zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.entityData$.subscribe(update => { + const entity = (update.data?.data ?? update.update ?? [])[0]; + if (!entity && !update.data) { + return; + } + const values = {...(update.data ? {} : this.apiUsage() ?? {})}; + this.apiKeys.forEach(key => { + const latest = entity?.latest?.[EntityKeyType.TIME_SERIES]?.[key]; + if (latest?.ts) { + const number = Number(latest.value); + values[key] = isFinite(number) ? number : 0; + } + }); + this.apiUsage.set(values); + this.chooseTab(); + }); + subscriber.subscribe(); + return subscriber; + } + + private chooseTab(): void { + const groups = this.groups(); + if (this.tabChosen || !groups.length) { + return; + } + this.tabChosen = true; + const [entities, api] = groups; + if (api.rows.some(row => row.critical) && !entities.rows.some(row => row.critical)) { + this.tab.set('api'); + } + } + + private toRow(name: string, used: number, limit: number): UsageRow { + const percent = limit ? Math.min(100, (used ?? 0) / limit * 100) : 0; + return {name, used: used ?? 0, limit: limit ?? 0, percent, critical: limit > 0 && percent >= CRITICAL_PERCENT}; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.scss new file mode 100644 index 0000000000..0d9797540e --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.scss @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-customize-home-panel .mat-mdc-dialog-surface { + border-radius: 14px; +} + +.tb-customize-home { + display: flex; + flex-direction: column; + gap: 8px; + box-sizing: border-box; + width: min(360px, calc(100vw - 32px)); + padding: 20px 20px 16px 24px; + + h2 { + margin: 0; + font: 500 17px/24px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-sections { + display: flex; + flex-direction: column; + margin: 0 -8px; + } + + .tb-section-row { + display: flex; + align-items: center; + gap: 12px; + height: 40px; + padding: 0 8px; + border-radius: 8px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.04); + } + + input { + flex: none; + width: 18px; + height: 18px; + margin: 0; + accent-color: var(--tb-primary-500); + cursor: pointer; + } + + .mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + } + + .tb-customize-actions { + display: flex; + align-items: center; + gap: 8px; + margin-top: 12px; + + .mdc-button { + height: 36px; + padding: 0 14px; + border-radius: 8px; + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.ts new file mode 100644 index 0000000000..4833927f84 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/customize-home-dialog.component.ts @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, ViewEncapsulation } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectHomeCards } from '@core/auth/auth.selectors'; +import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS, isHomeCardShown } from '@home/pages/home-page/home-cards.models'; + +export interface CustomizeHomeDialogData { + cards: HomeCardId[]; +} + +@Component({ + selector: 'tb-customize-home-dialog', + template: ` + + `, + styleUrls: ['./customize-home-dialog.component.scss'], + encapsulation: ViewEncapsulation.None, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class CustomizeHomeDialogComponent { + + readonly dialogRef = inject(MatDialogRef); + + private data = inject(MAT_DIALOG_DATA); + private store = inject(Store); + + private settings = toSignal(this.store.select(selectHomeCards), {initialValue: {}}); + + readonly rows = computed(() => this.data.cards.map(id => ({card: HOME_CARDS[id], shown: isHomeCardShown(this.settings(), id)}))); + + readonly anyHidden = computed(() => this.rows().some(row => !row.shown)); + + toggle(id: HomeCardId, shown: boolean): void { + this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: shown})); + } + + showAll(): void { + this.store.dispatch(new ActionPreferencesUpdateHomeCards(Object.fromEntries(this.data.cards.map(id => [id, true])))); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html new file mode 100644 index 0000000000..e11e8e8e79 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html @@ -0,0 +1,111 @@ + + + + @if (total()) { + + } + @if (canAdd) { + + add + {{ 'home.dashboards.add' | translate }} + + } + + @if (loaded()) { + @if (!total()) { +
+ + @if (canAdd) { + + } @else { +
{{ 'home.dashboards.none-assigned' | translate }}
+ } +
+ } @else { + @if (rows().length) { + + + + + + + + + + @for (row of rows(); track row.id) { + + + + + + } + +
{{ 'home.dashboards.name' | translate }}{{ 'home.dashboards.last-viewed' | translate }}
+ + {{ row.title | customTranslate }}{{ row.ago }}
+ } @else { +
{{ (tab() === 'last' ? 'home.dashboards.none-viewed' : 'home.dashboards.none-starred') | translate }}
+ } + @if (tab() === 'starred') { +
+ @if (picking()) { + +
+ @for (candidate of candidates(); track candidate.id; let i = $index) { +
+ star_border + {{ candidate.title | customTranslate }} + @if (candidate.ago) { + {{ candidate.ago }} + } +
+ } @empty { + @if (query().trim()) { +
{{ 'home.dashboards.no-match' | translate: {query: query().trim()} }}
+ } + } +
+ } @else { + + } +
+ } + + } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.scss new file mode 100644 index 0000000000..e302bc336a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.scss @@ -0,0 +1,304 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; +@use './home-table'; + +:host { + display: block; + min-width: 0; + container: tb-dashboards-home / inline-size; +} + +.tb-dashboards-table { + width: 100%; + border-collapse: collapse; + table-layout: auto; + + th { + height: 28px; + padding: 0 12px 0 0; + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.25px; + text-align: left; + white-space: nowrap; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + td { + height: 36px; + padding: 0 12px 0 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + vertical-align: middle; + font-variant-numeric: tabular-nums; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + tbody tr { + cursor: pointer; + + &:hover td { + background: rgba(0, 0, 0, 0.02); + } + + &:hover .col-title a { + text-decoration: underline; + } + } + + .col-star { + width: 40px; + min-width: 40px; + } + + td.col-title { + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + + a { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration: underline; + } + } + } + + .col-time { + width: 96px; + text-align: right; + white-space: nowrap; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } +} + +.tb-dashboards-star { + position: relative; + display: inline-flex; + margin: 0; + padding: 0; + border: 0; + background: none; + vertical-align: middle; + color: var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + cursor: pointer; + + &::after { + content: ''; + position: absolute; + inset: -4px; + border-radius: 50%; + } + + &:hover { + color: rgba(0, 0, 0, 0.18); + } + + &.starred { + color: var(--tb-primary-500); + + &:hover { + color: var(--tb-primary-700); + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 50%; + } + + .mat-icon { + color: inherit; + } +} + +.tb-dashboards-picker { + position: relative; +} + +.tb-dashboards-picker-add { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + width: 100%; + height: 40px; + margin: 0; + padding: 0 12px; + border: 1px dashed rgba(0, 0, 0, 0.2); + border-radius: 8px; + background: none; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + text-align: left; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + cursor: pointer; + transition: border-color .15s ease, color .15s ease, background-color .15s ease; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: inherit; + } + + &:hover { + border-color: var(--tb-primary-500); + background: color-mix(in srgb, var(--tb-primary-500) 4%, #fff); + color: var(--tb-primary-500); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + &:disabled { + border-style: solid; + border-color: rgba(0, 0, 0, 0.06); + background: none; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + cursor: default; + } +} + +.tb-dashboards-search { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + height: 40px; + padding: 0 4px 0 12px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.04); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + cursor: text; + + &:focus-within { + background: #fff; + box-shadow: 0 0 0 2px var(--tb-primary-500), 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); + color: var(--tb-primary-500); + } + + > .mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + color: inherit; + } + + input { + flex: 1; + min-width: 0; + border: 0; + outline: 0; + background: transparent; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + caret-color: var(--tb-primary-500); + + &::placeholder { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + } +} + +.tb-dashboards-search-close.mat-mdc-icon-button { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } + + .mat-mdc-button-touch-target { + width: 32px; + height: 32px; + } +} + +.tb-dashboards-options { + position: absolute; + top: calc(100% + 4px); + left: 0; + right: 0; + z-index: 5; + display: flex; + flex-direction: column; + max-height: 248px; + overflow-y: auto; + padding: 4px; + border-radius: 8px; + background: #fff; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.14), 0 1px 3px rgba(0, 0, 0, 0.08); + + &:empty { + display: none; + } +} + +.tb-dashboards-option { + display: flex; + align-items: center; + gap: 10px; + min-height: 40px; + padding: 0 10px; + border-radius: 6px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + cursor: pointer; + + .mat-icon { + flex: none; + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + small { + font-size: 12px; + white-space: nowrap; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + &.active { + background: rgba(0, 0, 0, 0.04); + + .mat-icon { + color: var(--tb-primary-500); + } + } +} + +.tb-dashboards-option-label { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.tb-dashboards-options-empty { + padding: 10px; + font-size: 13px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts new file mode 100644 index 0000000000..54925fa96e --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, inject, signal, viewChild } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { of, Subject } from 'rxjs'; +import { catchError, debounceTime, map, switchMap } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { UserSettingsService } from '@core/http/user-settings.service'; +import { DashboardService } from '@core/http/dashboard.service'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType } from '@shared/models/entity-type.models'; +import { HelpLinks } from '@shared/models/constants'; +import { PageLink } from '@shared/models/page/page-link'; +import { Direction } from '@shared/models/page/sort-order'; +import { HomeCardId, UserDashboardAction, UserDashboardsInfo } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { homeAgo, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; +import { MINUTE } from '@shared/models/time/time.models'; +import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; + +type DashboardsTab = 'last' | 'starred'; + +const SEARCH_SIZE = 10; +const FILL_SIZE = 20; + +export interface DashboardHomeRow { + id: string; + title: string; + starred: boolean; + lastVisited: number | null; + ago: string; + url: string; +} + +interface StarCandidate { + id: string; + title: string; + ago: string | null; +} + +@Component({ + selector: 'tb-dashboards-home', + templateUrl: './dashboards-home.component.html', + styleUrls: ['./dashboards-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class DashboardsHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.DASHBOARDS]; + + readonly tabOptions: HomeToggleOption[] = [ + {value: 'last', label: 'home.dashboards.last-viewed'}, + {value: 'starred', label: 'home.dashboards.starred'} + ]; + + readonly howToLink = HelpLinks.linksMap.dashboards; + + private store = inject(Store); + private router = inject(Router); + private translate = inject(TranslateService); + private userSettingsService = inject(UserSettingsService); + private dashboardService = inject(DashboardService); + private toast = inject(ToastNotificationService); + + private readonly authUser = getCurrentAuthUser(this.store); + private readonly fullscreen = getCurrentAuthState(this.store).forceFullscreen; + + readonly canAdd = inject(HomePermissionsService).canReadAllEntities(EntityType.DASHBOARD) && + inject(HomePermissionsService).canCreateEntities(EntityType.DASHBOARD); + readonly dashboardsLink = inject(HomePermissionsService).entitiesLink(EntityType.DASHBOARD); + readonly canUseIotHub = inject(HomePermissionsService).canUseIotHub(); + + readonly tab = signal('last'); + readonly expanded = signal(false); + readonly total = signal(null); + private readonly info = signal(null); + private readonly others = signal<{id: string; title: string}[]>([]); + private readonly now = signal(Date.now()); + + readonly picking = signal(false); + readonly query = signal(''); + readonly active = signal(0); + private readonly searchResults = signal([]); + private readonly search$ = new Subject(); + + private readonly searchInput = viewChild>('searchInput'); + + readonly loaded = computed(() => this.total() !== null && this.info() !== null); + + private readonly starredIds = computed(() => new Set((this.info()?.starred ?? []).map(dashboard => dashboard.id))); + + private readonly visits = computed(() => new Map((this.info()?.last ?? []).map(dashboard => [dashboard.id, dashboard.lastVisited]))); + + private readonly allRows = computed(() => { + const info = this.info(); + if (!info) { + return []; + } + const now = this.now(); + const starred = this.starredIds(); + const visits = this.visits(); + if (this.tab() === 'last') { + const viewed = [...info.last] + .sort((a, b) => b.lastVisited - a.lastVisited) + .map(dashboard => this.toRow(dashboard.id, dashboard.title, starred.has(dashboard.id), dashboard.lastVisited, now)); + const rest = this.others() + .filter(dashboard => !visits.has(dashboard.id)) + .map(dashboard => this.toRow(dashboard.id, dashboard.title, starred.has(dashboard.id), null, now)); + return [...viewed, ...rest]; + } + return [...info.starred] + .sort((a, b) => (visits.get(b.id) ?? 0) - (visits.get(a.id) ?? 0) || b.starredAt - a.starredAt) + .map(dashboard => this.toRow(dashboard.id, dashboard.title, true, visits.get(dashboard.id) ?? null, now)); + }); + + readonly listed = computed(() => this.tab() === 'last' ? Math.max(this.total() ?? 0, this.allRows().length) : this.allRows().length); + + readonly rows = computed(() => this.allRows().slice(0, homeListShown(this.listed(), this.expanded()))); + + readonly allStarred = computed(() => { + const total = this.total(); + return total !== null && total > 0 && this.starredIds().size >= total; + }); + + readonly candidates = computed(() => { + const starred = this.starredIds(); + if (this.query().trim()) { + return this.searchResults().filter(candidate => !starred.has(candidate.id)); + } + const now = this.now(); + return [...(this.info()?.last ?? [])] + .filter(dashboard => !starred.has(dashboard.id)) + .sort((a, b) => b.lastVisited - a.lastVisited) + .slice(0, SEARCH_SIZE) + .map(dashboard => ({id: dashboard.id, title: dashboard.title, ago: homeAgo(this.translate, now - dashboard.lastVisited)})); + }); + + constructor() { + if (this.dashboardsLink && this.authUser?.authority !== Authority.SYS_ADMIN) { + this.userSettingsService.getUserDashboardsInfo({ignoreLoading: true}).subscribe(info => { + this.info.set({last: info?.last ?? [], starred: info?.starred ?? []}); + }); + this.dashboardService.getUserDashboards(this.authUser.userId, null, + new PageLink(FILL_SIZE, 0, null, {property: 'createdTime', direction: Direction.DESC}), {ignoreLoading: true}).pipe( + catchError(() => of(null)) + ).subscribe(page => { + this.others.set((page?.data ?? []).map(dashboard => ({id: dashboard.id.id, title: dashboard.title}))); + this.total.set(page?.totalElements ?? 0); + }); + } else { + this.info.set({last: [], starred: []}); + this.total.set(0); + } + this.search$.pipe( + debounceTime(200), + switchMap(query => query + ? this.dashboardService.getUserDashboards(this.authUser.userId, null, + new PageLink(SEARCH_SIZE + this.starredIds().size, 0, query, {property: 'title', direction: Direction.ASC}), {ignoreLoading: true}).pipe( + map(page => page.data.map(dashboard => { + const visited = this.visits().get(dashboard.id.id); + return {id: dashboard.id.id, title: dashboard.title, ago: visited ? homeAgo(this.translate, Date.now() - visited) : null}; + })), + catchError(() => of([])) + ) + : of([])), + takeUntilDestroyed() + ).subscribe(results => { + this.searchResults.set(results); + this.active.set(0); + }); + const tick = setInterval(() => this.now.set(Date.now()), MINUTE); + inject(DestroyRef).onDestroy(() => clearInterval(tick)); + } + + setTab(tab: DashboardsTab): void { + this.tab.set(tab); + this.closePicker(); + } + + open(row: DashboardHomeRow): void { + this.router.navigateByUrl(row.url); + } + + toggleStar(row: DashboardHomeRow, $event: Event): void { + $event.stopPropagation(); + const info = this.info(); + if (!info) { + return; + } + if (row.starred) { + this.info.set({...info, starred: info.starred.filter(dashboard => dashboard.id !== row.id)}); + this.userSettingsService.reportUserDashboardAction(row.id, UserDashboardAction.UNSTAR, {ignoreLoading: true}).subscribe(); + } else { + this.star(row.id, row.title); + } + } + + openPicker(): void { + this.query.set(''); + this.searchResults.set([]); + this.active.set(0); + this.picking.set(true); + setTimeout(() => this.searchInput()?.nativeElement.focus()); + } + + closePicker(): void { + this.picking.set(false); + } + + onQuery(value: string): void { + this.query.set(value); + this.active.set(0); + this.search$.next(value.trim()); + } + + onPickerKeydown(event: KeyboardEvent): void { + const count = this.candidates().length; + if (event.key === 'ArrowDown' && count) { + event.preventDefault(); + this.active.set((this.active() + 1) % count); + } else if (event.key === 'ArrowUp' && count) { + event.preventDefault(); + this.active.set((this.active() - 1 + count) % count); + } else if (event.key === 'Enter') { + event.preventDefault(); + const candidate = this.candidates()[this.active()]; + if (candidate) { + this.pick(candidate); + } + } else if (event.key === 'Escape') { + event.preventDefault(); + this.closePicker(); + } + } + + onPickerBlur(): void { + if (document.hasFocus()) { + this.closePicker(); + } + } + + pick(candidate: StarCandidate): void { + this.closePicker(); + this.star(candidate.id, candidate.title); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.dashboards.starred-toast', {title: candidate.title}))); + } + + private star(id: string, title: string): void { + const info = this.info(); + if (!info || this.starredIds().has(id)) { + return; + } + this.info.set({...info, starred: [...info.starred, {id, title, starred: true, starredAt: Date.now()}]}); + this.userSettingsService.reportUserDashboardAction(id, UserDashboardAction.STAR, {ignoreLoading: true}).subscribe(); + } + + private toRow(id: string, title: string, starred: boolean, lastVisited: number | null, now: number): DashboardHomeRow { + return { + id, + title, + starred, + lastVisited, + ago: lastVisited ? homeAgo(this.translate, now - lastVisited) : '', + url: (this.fullscreen ? '/dashboard/' : '/dashboards/all/') + id + }; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.html new file mode 100644 index 0000000000..f8d917b85d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.html @@ -0,0 +1,34 @@ + + + {{ 'home.activity.period' | translate }} + + @if (loaded() && !empty() && series.length > 1) { + + } + + @if (empty()) { +
+ +
{{ (sysAdmin ? 'home.activity.no-messages' : 'home.activity.none') | translate }}
+
+ } @else { +
+ @for (series of series; track series.id) { +
+
{{ series.label | translate }}
+ @if (series.id === 'devices') { + + } @else { + + } +
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.scss new file mode 100644 index 0000000000..f379e7962a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.scss @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; + +:host { + display: block; + min-width: 0; + container: tb-activity-home / inline-size; +} + +.tb-activity-period { + margin-left: 4px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-activity-series { + min-width: 0; +} + +.tb-activity-pair[data-tab="devices"] .tb-activity-series[data-series="messages"], +.tb-activity-pair[data-tab="messages"] .tb-activity-series[data-series="devices"] { + display: none; +} + +.tb-activity-name { + display: none; + margin: 0 0 8px 36px; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-activity-chart { + height: 130px; +} + +@container tb-activity-home (min-width: 560px) { + .tb-activity-toggle { + display: none; + } + + .tb-activity-pair { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + column-gap: 32px; + } + + .tb-activity-pair[data-tab] .tb-activity-series[data-series] { + display: block; + } + + .tb-activity-name { + display: block; + } +} + +.tb-activity-pair.single { + display: block; + + .tb-activity-name { + display: block; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts new file mode 100644 index 0000000000..b34021b089 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + NgZone, + Renderer2, + signal, + viewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; +import * as echarts from 'echarts/core'; +import tinycolor from 'tinycolor2'; +import { CallbackDataParams } from 'echarts/types/dist/shared'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; +import { AggregationType, DAY } from '@shared/models/time/time.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; +import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } from '@home/pages/home-page/home-chart.models'; + +type ActivitySeries = 'devices' | 'messages'; + +const DAYS = 30; +const LABEL_STEP = 7; +const SCALE_STEPS = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, + 1e6, 2e6, 5e6, 1e7, 2e7, 5e7, 1e8, 2e8, 5e8, 1e9]; + +const startOfFirstDay = (now: number): number => { + const date = new Date(now - (DAYS - 1) * DAY); + date.setHours(0, 0, 0, 0); + return date.getTime(); +}; + +const shortNumber = (value: number): string => { + const units: [number, string][] = [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']]; + const unit = units.find(([size]) => value >= size); + if (!unit) { + return `${Math.round(value)}`; + } + return `${(Math.floor(value / unit[0] * 10) / 10).toString().replace(/\.0$/, '')}${unit[1]}`; +}; + +const scale = (points: [number, number][]): {max: number; interval: number} => { + const top = Math.max(0, ...points.map(point => point[1])); + const step = SCALE_STEPS.find(value => top / value <= 4) ?? SCALE_STEPS[SCALE_STEPS.length - 1]; + const max = Math.max(step, Math.ceil(top / step) * step); + return {max, interval: (max / step) % 2 === 0 ? max / 2 : max}; +}; +const LIMIT = 25000; +const AXIS_LABEL = {color: 'rgba(0, 0, 0, 0.56)', fontFamily: 'Roboto', fontSize: 12, fontWeight: 400, lineHeight: 16}; + +interface ActivitySeriesConfig { + id: ActivitySeries; + key: string; + label: string; + daily: boolean; +} + +const SERIES: ActivitySeriesConfig[] = [ + {id: 'devices', key: 'activeDevicesCountHourly', label: 'home.activity.devices', daily: false}, + {id: 'messages', key: 'transportMsgCountHourly', label: 'home.activity.messages', daily: true} +]; + +@Component({ + selector: 'tb-devices-activity-home', + templateUrl: './devices-activity-home.component.html', + styleUrls: ['./devices-activity-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class DevicesActivityHomeComponent implements AfterViewInit { + + readonly card = HOME_CARDS[HomeCardId.ACTIVITY]; + + readonly sysAdmin = getCurrentAuthUser(inject(Store))?.authority === Authority.SYS_ADMIN; + + readonly series = this.sysAdmin ? SERIES.filter(series => series.id === 'messages') : SERIES; + + readonly tabOptions: HomeToggleOption[] = this.series.map(series => ({value: series.id, label: series.label})); + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private renderer = inject(Renderer2); + private translate = inject(TranslateService); + private host = inject>(ElementRef); + + readonly tab = signal(this.series[0].id); + private readonly data = signal | null>(null); + + readonly loaded = computed(() => this.data() !== null); + readonly empty = computed(() => { + const data = this.data(); + return !!data && this.series.every(series => !data[series.id].some(point => point[1] > 0)); + }); + + private readonly devicesChart = viewChild>('devicesChart'); + private readonly messagesChart = viewChild>('messagesChart'); + + private charts: Partial> = {}; + private subscribers: TelemetrySubscriber[] = []; + private resizeObserver: ResizeObserver; + + private endTs = Date.now(); + + private startTs = startOfFirstDay(this.endTs); + + private readonly raw: Record> = {devices: new Map(), messages: new Map()}; + + private historyLoaded = false; + + private subscriber: TelemetrySubscriber | null = null; + + private dayTimer: ReturnType | null = null; + + constructor() { + this.subscribe(); + inject(DestroyRef).onDestroy(() => { + this.subscriber?.unsubscribe(); + clearTimeout(this.dayTimer); + this.resizeObserver?.disconnect(); + Object.values(this.charts).forEach(chart => chart.dispose()); + }); + } + + private subscribe(): void { + this.subscriber?.unsubscribe(); + this.endTs = Date.now(); + this.startTs = startOfFirstDay(this.endTs); + this.historyLoaded = false; + SERIES.forEach(series => this.raw[series.id].clear()); + const keys = this.series.map(series => series.key); + const cmd = new EntityDataCmd(); + cmd.query = { + entityFilter: {type: AliasFilterType.apiUsageState}, + pageLink: {page: 0, pageSize: 1}, + entityFields: [], + latestValues: keys.map(key => ({type: EntityKeyType.TIME_SERIES, key})) + }; + cmd.historyCmd = { + keys, + startTs: this.startTs, + endTs: this.endTs, + intervalType: IntervalType.MILLISECONDS, + interval: 1000, + timeZoneId: Intl.DateTimeFormat().resolvedOptions().timeZone, + limit: LIMIT, + agg: AggregationType.NONE + }; + cmd.latestCmd = {keys: keys.map(key => ({type: EntityKeyType.TIME_SERIES, key}))}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.entityData$.subscribe(update => { + const entities = update.data?.data ?? update.update ?? []; + entities.forEach(entity => { + this.series.forEach(series => { + (entity.timeseries?.[series.key] ?? []).forEach(value => this.put(series.id, value.ts, value.value)); + const latest = entity.latest?.[EntityKeyType.TIME_SERIES]?.[series.key]; + if (latest?.ts) { + this.put(series.id, latest.ts, latest.value); + } + }); + }); + if (update.data) { + this.historyLoaded = true; + } + if (this.historyLoaded) { + this.refresh(); + } + }); + subscriber.subscribe(); + this.subscriber = subscriber; + clearTimeout(this.dayTimer); + this.dayTimer = setTimeout(() => this.subscribe(), this.dayStart(DAYS) - Date.now() + 1000); + } + + private put(series: ActivitySeries, ts: number, value: string): void { + const number = Number(value); + if (ts >= this.startTs && !isNaN(number)) { + this.raw[series].set(ts, number); + } + } + + private refresh(): void { + this.endTs = Math.max(this.endTs, Date.now()); + const points = (series: ActivitySeries) => [...this.raw[series].entries()].sort((a, b) => a[0] - b[0]); + this.data.set({ + devices: points('devices').map(([ts, value]) => [ts - this.startTs, value] as [number, number]), + messages: this.dailyBuckets(points('messages')) + }); + setTimeout(() => this.render()); + } + + ngAfterViewInit(): void { + this.resizeObserver = new ResizeObserver(() => Object.values(this.charts).forEach(chart => chart.resize())); + this.resizeObserver.observe(this.host.nativeElement); + } + + private dailyBuckets(values: [number, number][]): [number, number][] { + const buckets: [number, number][] = Array.from({length: DAYS}, (_, index) => [this.dayStart(index) - this.startTs, 0]); + buckets[DAYS - 1][0] = this.endTs - this.startTs; + values.forEach(([ts, value]) => { + const index = buckets.findIndex((_, day) => ts < this.dayStart(day + 1)); + if (ts >= this.startTs && index > -1) { + buckets[index][1] += value; + } + }); + return buckets; + } + + private dayStart(index: number): number { + const date = new Date(this.startTs); + date.setDate(date.getDate() + index); + return date.getTime(); + } + + private xLabel(offset: number): string { + const span = this.endTs - this.startTs; + if (offset >= span - 1000) { + return this.translate.instant('home.activity.today'); + } + if (offset > span - (LABEL_STEP - 1) * DAY) { + return ''; + } + const date = new Date(this.dayStart(Math.round(offset / DAY))); + return `${String(date.getDate()).padStart(2, '0')} ${date.toLocaleString(this.translate.currentLang?.replace('_', '-') || 'en-US', {month: 'short'})}`; + } + + private tooltipHeader(series: ActivitySeriesConfig, offset: number): string { + const span = this.endTs - this.startTs; + const date = new Date(this.startTs + offset); + const day = `${String(date.getDate()).padStart(2, '0')} ${date.toLocaleString(this.translate.currentLang?.replace('_', '-') || 'en-US', {month: 'short'})}`; + if (series.daily) { + return offset >= span - 1000 ? this.translate.instant('home.activity.today') : day; + } + return `${day}, ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + } + + setTab(tab: ActivitySeries): void { + this.tab.set(tab); + setTimeout(() => Object.values(this.charts).forEach(chart => chart.resize())); + } + + private render(): void { + const data = this.data(); + if (!data || this.empty()) { + return; + } + echartsModule.init(); + const color = getComputedStyle(this.host.nativeElement).getPropertyValue('--tb-primary-500').trim() || '#305680'; + this.series.forEach(series => { + const element = (series.id === 'devices' ? this.devicesChart() : this.messagesChart())?.nativeElement; + if (!element) { + return; + } + let chart = this.charts[series.id]; + if (chart && chart.getDom() !== element) { + chart.dispose(); + chart = null; + } + if (!chart) { + this.renderer.setStyle(element, 'letterSpacing', 'normal'); + chart = echarts.init(element, null, {renderer: 'svg'}); + this.charts[series.id] = chart; + } + chart.setOption(this.option(series, data[series.id], color), true); + }); + } + + private option(series: ActivitySeriesConfig, points: [number, number][], color: string): EChartsOption { + const label = this.translate.instant(series.label); + const span = this.endTs - this.startTs; + const yScale = scale(points); + return { + backgroundColor: 'transparent', + tooltip: [{ + ...homeChartTooltipOptions, + formatter: (params: CallbackDataParams[]) => { + const param = params.find(item => item.seriesId === series.id); + return param ? homeChartTooltipHtml(this.tooltipHeader(series, Number(param.value[0])), + [{color, name: label, value: shortNumber(Number(param.value[1]))}]) : ''; + } + }], + grid: [{left: 36, right: 28, top: 6, bottom: 26, containLabel: false}], + xAxis: [{ + type: 'value', + min: 0, + max: span, + interval: LABEL_STEP * DAY, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: false}, + axisLabel: { + ...AXIS_LABEL, + margin: 12, + showMinLabel: true, + showMaxLabel: true, + alignMinLabel: 'left', + alignMaxLabel: 'right', + formatter: (value: number) => this.xLabel(value) + } + }], + yAxis: [{ + type: 'value', + min: 0, + max: yScale.max, + interval: yScale.interval, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: true, lineStyle: {color: 'rgba(0, 0, 0, 0.06)', width: 1}}, + axisLabel: { + ...AXIS_LABEL, + margin: 8, + formatter: (value: number) => value >= 1e6 ? `${value / 1e6}M` : value >= 1000 ? `${value / 1000}k` : `${value}` + } + }], + series: [{ + id: series.id, + type: 'line', + name: label, + color, + smooth: false, + showSymbol: false, + ...homeChartHoverSymbol(color), + lineStyle: {width: 2, color, cap: 'round', join: 'round'}, + areaStyle: { + color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ + {offset: 0, color: tinycolor(color).setAlpha(0.12).toRgbString()}, + {offset: 1, color: tinycolor(color).setAlpha(0).toRgbString()} + ]) + }, + data: points + }, { + id: `${series.id}-now`, + type: 'line', + silent: true, + tooltip: {show: false}, + showSymbol: true, + symbol: 'circle', + symbolSize: 8, + z: 3, + itemStyle: {color, borderColor: '#fff', borderWidth: 2}, + lineStyle: {width: 0}, + label: { + show: true, + position: 'right', + distance: 3, + color: 'rgba(0, 0, 0, 0.76)', + fontFamily: 'Roboto', + fontSize: 12, + fontWeight: 500, + lineHeight: 16, + formatter: (param: CallbackDataParams) => shortNumber(Number(param.value[1])) + }, + data: points.length ? [points[points.length - 1]] : [] + }], + animation: true, + animationThreshold: 2000, + animationDuration: 200, + animationEasing: 'cubicOut', + animationDelay: 0, + animationDurationUpdate: 300, + animationEasingUpdate: 'cubicOut', + animationDelayUpdate: 0 + }; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html new file mode 100644 index 0000000000..cfc7ac383b --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html @@ -0,0 +1,102 @@ + + + + @if (canAdd) { + + add + {{ 'home.devices.add' | translate }} + + } + + @if (total() === 0) { +
+ + @if (canAdd) { + + } @else { +
{{ 'home.devices.none-assigned' | translate }}
+ } +
+ } @else if (total()) { +
+ @for (tile of tiles(); track tile.state) { + + } +
+ @if (allActive()) { +
+ + {{ (total() === 1 ? 'home.devices.one-active' : 'home.devices.all-active') | translate: {count: total()} }} +
+ } + @if (rows().length) { + + + + + + + + + + + @for (row of rows(); track row.id) { + + + + + @if (row.lastActivity) { + + } @else { + + } + + } + +
+ + {{ 'home.devices.profile' | translate }}{{ 'home.devices.state' | translate }} + +
+ + @if (row.url) { + {{ row.name }} + } @else { + {{ row.name }} + } + + {{ row.profile }} + {{ row.profile }} + + {{ (row.active ? 'home.devices.active' : 'home.devices.inactive') | translate }} + + {{ row.ago }}{{ 'home.devices.never' | translate }}
+ } @else if (loaded()) { +
{{ ('home.devices.none-' + (filter() ?? 'active')) | translate }}
+ } + + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.scss new file mode 100644 index 0000000000..a389b202f2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.scss @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; +@use './home-table'; + +:host { + display: block; + min-width: 0; + container: tb-devices-home / inline-size; +} + +.tb-home-tile { + &.inactive:not(.zero) { + --tb-sel: var(--tb-crit, #D12730); + } + + &.active { + --tb-sel: var(--tb-ok, #198038); + } +} + +.tb-devices-table { + .tb-devices-cell-main { + display: flex; + min-width: 0; + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + } + + td.col-profile { + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .col-state { + white-space: nowrap; + } +} + +.tb-devices-cell-sub { + display: none; + overflow: hidden; + font-size: 12px; + line-height: 16px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-devices-state { + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 13px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + &::before { + content: ''; + box-sizing: border-box; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &.active::before { + background: var(--tb-ok, #198038); + } + + &.inactive::before { + border: 2px solid var(--tb-crit, #D12730); + background: transparent; + } +} + +.tb-devices-never { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} + +@container tb-devices-home (max-width: 599px) { + .tb-devices-state { + gap: 0; + } + + .tb-devices-state-word, .tb-devices-table th.col-state .th-text { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + } +} + +@container tb-devices-home (max-width: 459px) { + .tb-devices-table { + .col-profile { + display: none; + } + + td.col-name { + width: 99%; + padding-top: 6px; + padding-bottom: 6px; + } + + .tb-devices-cell-main { + max-width: none; + } + } + + .tb-devices-cell-sub { + display: block; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts new file mode 100644 index 0000000000..fb68fc1bd8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts @@ -0,0 +1,343 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + inject, + NgZone, + signal, + untracked, + WritableSignal +} from '@angular/core'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { take } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { selectPersistDeviceStateToTelemetry } from '@core/auth/auth.selectors'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; +import { EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityType } from '@shared/models/entity-type.models'; +import { + BooleanOperation, + EntityData, + EntityDataPageLink, + EntityKey, + EntityKeyType, + EntityKeyValueType, + FilterPredicateType, + KeyFilter, + NumericOperation +} from '@shared/models/query/query.models'; +import { Direction } from '@shared/models/page/sort-order'; +import { HelpLinks } from '@shared/models/constants'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { MINUTE } from '@shared/models/time/time.models'; +import { homeAgo, homeListPageSize, homeListShown } from '@home/pages/home-page/home-list.models'; + +type DeviceState = 'inactive' | 'active'; +type DeviceSortKey = 'last' | 'name'; + +interface DeviceQuery { + state: DeviceState | null; + sortKey: EntityKey; + direction: Direction; + withActivity?: boolean; + neverConnected?: boolean; + counted: boolean; +} + +interface DeviceTile { + state: DeviceState; + count: number; + pressed: boolean; +} + +export interface DeviceHomeRow { + id: string; + name: string; + profile: string; + active: boolean; + lastActivity: number | null; + ago: string; + url: string; +} + +@Component({ + selector: 'tb-devices-home', + templateUrl: './devices-home.component.html', + styleUrls: ['./devices-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class DevicesHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.DEVICES]; + + readonly howToLink = HelpLinks.linksMap.devices; + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private store = inject(Store); + private router = inject(Router); + private translate = inject(TranslateService); + private permissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); + + readonly canAdd = this.permissions.canReadAllEntities(EntityType.DEVICE) && this.permissions.canCreateEntities(EntityType.DEVICE); + readonly devicesLink = this.permissions.entitiesLink(EntityType.DEVICE); + + readonly filter = signal(null); + readonly expanded = signal(false); + readonly sortKey = signal('last'); + readonly sortDesc = signal(true); + + readonly total = signal(null); + readonly inactive = signal(null); + readonly active = signal(null); + + private readonly stateKeyType = signal(null); + private readonly lists = signal<(EntityData[] | null)[]>([]); + private readonly listTotals = signal([]); + private readonly now = signal(Date.now()); + + private dataSubscribers: TelemetrySubscriber[] = []; + + readonly tiles = computed(() => { + const filter = this.filter(); + return [ + {state: 'inactive', count: this.inactive() ?? 0, pressed: filter === 'inactive'}, + {state: 'active', count: this.active() ?? 0, pressed: filter === 'active'} + ]; + }); + + readonly allActive = computed(() => !this.filter() && this.inactive() === 0 && !!this.total()); + + readonly loaded = computed(() => this.lists().length > 0 && this.lists().every(list => list !== null)); + + readonly listed = computed(() => this.listTotals().reduce((sum, count, index) => + this.listQueries[index]?.counted ? sum + count : sum, 0)); + + private listQueries: DeviceQuery[] = []; + + readonly rows = computed(() => { + const keyType = this.stateKeyType(); + const now = this.now(); + const merged = this.lists().flatMap((list, index) => { + const rows = list ?? []; + return this.listQueries[index]?.neverConnected && keyType + ? rows.filter(data => !Number(data.latest?.[keyType]?.lastActivityTime?.value)) + : rows; + }); + return merged.slice(0, homeListShown(this.listed(), this.expanded())).map(data => this.toRow(data, keyType, now)); + }); + + readonly viewAllParams = computed(() => { + const filter = this.filter(); + return filter && this.devicesLink?.endsWith('/all') ? {active: filter === 'active'} : null; + }); + + private readonly queries = computed(() => { + const keyType = this.stateKeyType(); + if (!keyType) { + return []; + } + const filter = this.filter(); + const desc = this.sortDesc(); + if (this.sortKey() === 'name') { + return [{state: filter, sortKey: {type: EntityKeyType.ENTITY_FIELD, key: 'name'}, direction: desc ? Direction.DESC : Direction.ASC, counted: true}]; + } + const lastActivity: EntityKey = {type: keyType, key: 'lastActivityTime'}; + const silent: DeviceQuery = {state: 'inactive', sortKey: lastActivity, direction: desc ? Direction.DESC : Direction.ASC, + withActivity: true, counted: false}; + const never: DeviceQuery = {state: 'inactive', sortKey: lastActivity, direction: Direction.DESC, neverConnected: true, counted: true}; + const active: DeviceQuery = {state: 'active', sortKey: lastActivity, direction: desc ? Direction.ASC : Direction.DESC, counted: true}; + const inactive = desc ? [silent, never] : [never, silent]; + if (filter === 'inactive') { + return inactive; + } + if (filter === 'active') { + return [active]; + } + return desc ? [...inactive, active] : [active, ...inactive]; + }); + + constructor() { + this.store.select(selectPersistDeviceStateToTelemetry).pipe(take(1)).subscribe(persisted => { + const keyType = persisted ? EntityKeyType.TIME_SERIES : EntityKeyType.SERVER_ATTRIBUTE; + this.subscribeCount(this.total); + this.subscribeCount(this.inactive, this.activeFilter(keyType, false)); + this.subscribeCount(this.active, this.activeFilter(keyType, true)); + this.stateKeyType.set(keyType); + }); + effect(() => { + const queries = this.queries(); + const pageSize = homeListPageSize(this.expanded()); + untracked(() => this.subscribeLists(queries, pageSize)); + }); + const tick = setInterval(() => this.now.set(Date.now()), MINUTE); + inject(DestroyRef).onDestroy(() => { + clearInterval(tick); + this.dataSubscribers.forEach(subscriber => subscriber.unsubscribe()); + }); + } + + pick(tile: DeviceTile): void { + if (tile.count || tile.pressed) { + this.filter.set(tile.pressed ? null : tile.state); + } + } + + sortBy(key: DeviceSortKey): void { + if (this.sortKey() === key) { + this.sortDesc.set(!this.sortDesc()); + } else { + this.sortKey.set(key); + this.sortDesc.set(key === 'last'); + } + } + + ariaSort(key: DeviceSortKey): string { + if (this.sortKey() !== key) { + return 'none'; + } + return this.sortDesc() ? 'descending' : 'ascending'; + } + + sortIcon(key: DeviceSortKey): string { + if (key === 'name') { + return this.sortKey() === 'name' && this.sortDesc() ? 'arrow_downward' : 'arrow_upward'; + } + return this.sortKey() === 'last' && !this.sortDesc() ? 'arrow_upward' : 'arrow_downward'; + } + + open(row: DeviceHomeRow): void { + if (row.url) { + this.router.navigateByUrl(row.url); + } + } + + private subscribeLists(queries: DeviceQuery[], pageSize: number): void { + this.dataSubscribers.forEach(subscriber => subscriber.unsubscribe()); + const keyType = this.stateKeyType(); + if (!keyType || !queries.length) { + this.dataSubscribers = []; + return; + } + this.listQueries = queries; + const previous = this.lists(); + const previousTotals = this.listTotals(); + this.lists.set(queries.map((_, index) => previous[index] ?? null)); + this.listTotals.set(queries.map((_, index) => previousTotals[index] ?? 0)); + this.dataSubscribers = queries.map((query, index) => { + const cmd = new EntityDataCmd(); + const pageLink: EntityDataPageLink = { + page: 0, + pageSize: query.neverConnected ? pageSize * 2 : pageSize, + sortOrder: {key: query.sortKey, direction: query.direction}, + dynamic: true + }; + cmd.query = { + entityFilter: {type: AliasFilterType.entityType, entityType: EntityType.DEVICE}, + pageLink, + keyFilters: [ + ...(query.state ? this.activeFilter(keyType, query.state === 'active') : []), + ...(query.withActivity ? [this.hasActivityFilter(keyType)] : []) + ], + entityFields: [ + {type: EntityKeyType.ENTITY_FIELD, key: 'name'}, + {type: EntityKeyType.ENTITY_FIELD, key: 'type'} + ], + latestValues: [ + {type: keyType, key: 'active'}, + {type: keyType, key: 'lastActivityTime'} + ] + }; + cmd.latestCmd = {keys: [{type: keyType, key: 'active'}, {type: keyType, key: 'lastActivityTime'}]}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.entityData$.subscribe(update => { + if (update.data) { + this.setList(index, update.data.data, update.data.totalElements); + } else if (update.update) { + const list = this.lists()[index] ?? []; + const byId = new Map(update.update.map(data => [data.entityId.id, data])); + this.setList(index, list.map(data => this.merge(data, byId.get(data.entityId.id))), null); + } + }); + subscriber.subscribe(); + return subscriber; + }); + } + + private setList(index: number, data: EntityData[], total: number | null): void { + const lists = [...this.lists()]; + lists[index] = data; + this.lists.set(lists); + if (total !== null) { + const totals = [...this.listTotals()]; + totals[index] = total; + this.listTotals.set(totals); + } + } + + private merge(current: EntityData, update?: EntityData): EntityData { + if (!update) { + return current; + } + const latest = {...current.latest}; + Object.keys(update.latest ?? {}).forEach(type => latest[type] = {...(latest[type] ?? {}), ...update.latest[type]}); + return {...current, latest}; + } + + private subscribeCount(target: WritableSignal, keyFilters?: KeyFilter[]): void { + this.homeCounts.watchEntityCount(EntityType.DEVICE, count => target.set(count), this.destroyRef, keyFilters); + } + + private activeFilter(keyType: EntityKeyType, active: boolean): KeyFilter[] { + return [{ + key: {type: keyType, key: 'active'}, + valueType: EntityKeyValueType.BOOLEAN, + predicate: { + type: FilterPredicateType.BOOLEAN, + operation: BooleanOperation.EQUAL, + value: {defaultValue: active} + } + }]; + } + + private hasActivityFilter(keyType: EntityKeyType): KeyFilter { + return { + key: {type: keyType, key: 'lastActivityTime'}, + valueType: EntityKeyValueType.NUMERIC, + predicate: { + type: FilterPredicateType.NUMERIC, + operation: NumericOperation.GREATER, + value: {defaultValue: 0} + } + }; + } + + private toRow(data: EntityData, keyType: EntityKeyType | null, now: number): DeviceHomeRow { + const fields = data.latest?.[EntityKeyType.ENTITY_FIELD] ?? {}; + const state = keyType ? data.latest?.[keyType] ?? {} : {}; + const lastActivity = Number(state.lastActivityTime?.value) || null; + return { + id: data.entityId.id, + name: fields.name?.value ?? '', + profile: fields.type?.value ?? '', + active: state.active?.value === 'true', + lastActivity, + ago: lastActivity ? homeAgo(this.translate, now - lastActivity) : '', + url: this.permissions.entityDetailsLink(EntityType.DEVICE, data.entityId.id) + }; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html new file mode 100644 index 0000000000..c7f1cb015a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html @@ -0,0 +1,63 @@ + + + @if (loaded()) { +
    + @for (step of steps; track step.key; let i = $index) { +
  1. +
    + + +
    + @if (open() === i) { +
    +
    + {{ 'home.get-started.step-of' | translate: {step: i + 1, total: steps.length} }} + {{ 'home.get-started.' + step.key + '.title' | translate }} +
    +

    {{ 'home.get-started.' + step.key + '.text' | translate }} + {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }} +

    + @if (step.code) { +
    {{ step.code }}
    + } + @if (step.link || !isDone(i)) { +
    + @if (step.link) { + {{ 'home.get-started.open' | translate: {page: (step.page | translate)} }} + } + + @if (!isDone(i)) { + + } +
    + } +
    + } +
  2. + } +
+ @if (allDone()) { +
+ +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss new file mode 100644 index 0000000000..c2b73ddfeb --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '../../../components/ai/ai-code-blocks' as *; +@use './home-table'; + +:host { + --tb-home-card-padding: 16px 20px 20px; + --tb-home-card-gap: 8px; + --tb-home-card-header-height: 32px; + display: block; + min-width: 0; + container: tb-get-started-home / inline-size; +} + +.tb-gs-steps { + display: grid; + gap: 2px; + margin: 0 -8px; + padding: 0; + list-style: none; + + li { + min-width: 0; + border-radius: 10px; + + &.open { + background: rgba(0, 0, 0, 0.03); + } + } +} + +.tb-gs-row { + display: flex; + align-items: center; + gap: 10px; + padding: 0 8px; +} + +.tb-gs-mark { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 22px; + height: 22px; + margin: 0; + padding: 0; + border: 1.5px solid var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + border-radius: 50%; + background: #fff; + font: 500 12px/1 var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-60, rgba(0, 0, 0, 0.6)); + cursor: pointer; + transition: border-color .15s ease, background-color .15s ease, color .15s ease; + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + color: inherit; + } + + &:hover { + border-color: var(--tb-ok, #198038); + color: var(--tb-ok, #198038); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } +} + +li.done .tb-gs-mark { + border-color: transparent; + background: var(--tb-ok-tint, rgba(25, 128, 56, 0.08)); + color: var(--tb-ok, #198038); +} + +.tb-gs-title { + display: flex; + flex: 1; + align-items: center; + min-width: 0; + height: 36px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: .2px; + text-align: left; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + cursor: pointer; + + > span { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } +} + +li.open .tb-gs-title { + font-weight: 500; +} + +li.done:not(.open) .tb-gs-title { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-gs-body { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 8px; + min-width: 0; + padding: 0 12px 8px 40px; + + p { + margin: 0; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + letter-spacing: .2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } +} + +.tb-gs-head { + display: none; +} + +.tb-gs-guide { + border-radius: 4px; + font-weight: 500; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + white-space: nowrap; + color: var(--tb-primary-500); + transition: text-decoration-color .15s ease; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration-color: currentColor; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + .mat-icon { + width: 14px; + height: 14px; + margin-left: 2px; + font-size: 14px; + line-height: 14px; + vertical-align: -2px; + } +} + +:host ::ng-deep .tb-gs-code { + min-width: 0; + + @include ai-code-blocks; + + .tb-codeblock { + min-width: 0; + + .tb-code { + padding: 10px 12px 12px; + white-space: pre; + overflow-wrap: normal; + overflow-x: auto; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.2) transparent; + } + } +} + +.tb-gs-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; +} + +.tb-gs-spacer { + flex: 1 1 auto; + min-width: 0; +} + +.tb-gs-open.mat-mdc-outlined-button { + height: 32px; + padding: 0 16px; + border-radius: 4px; + background: #fff; + + &:hover, &:focus, &:active { + border-bottom-color: rgba(0, 0, 0, 0.1); + } +} + +.tb-gs-done.mat-mdc-button, .tb-gs-again .mat-mdc-button { + height: 32px; + padding: 0 8px; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } +} + +.tb-gs-done.mat-mdc-button { + margin-right: -8px; +} + +.tb-gs-again { + display: flex; + margin: 4px 0 -6px -8px; +} + +@container tb-get-started-home (min-width: 600px) { + .tb-gs-body { + gap: 12px; + padding: 20px 24px; + + p { + max-width: 52ch; + font-size: 14px; + line-height: 22px; + letter-spacing: .1px; + } + } + + .tb-gs-head { + display: flex; + flex-direction: column; + gap: 2px; + } + + .tb-gs-head-n { + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: .4px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + .tb-gs-head-t { + font: 500 16px/24px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-gs-open.mat-mdc-outlined-button, .tb-gs-done.mat-mdc-button { + height: 36px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts new file mode 100644 index 0000000000..7628503b41 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterNextRender, + ChangeDetectionStrategy, + Component, + computed, + effect, + ElementRef, + inject, + Injector, + signal, + untracked +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { UserSettingsService } from '@core/http/user-settings.service'; +import { WhiteLabelingService } from '@core/http/white-labeling.service'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { baseUrl } from '@core/utils'; +import { GettingStarted, HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; +import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; + +export interface GetStartedStep { + key: string; + doc: string; + link?: string; + page?: string; + code?: string; +} + +const sendCommand = (temperature: number): string => + `curl -X POST ${baseUrl()}/api/v1/$ACCESS_TOKEN/telemetry \\\n -H "Content-Type: application/json" \\\n -d '{"temperature": ${temperature}}'`; + +@Component({ + selector: 'tb-get-started-home', + templateUrl: './get-started-home.component.html', + styleUrls: ['./get-started-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class GetStartedHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.GET_STARTED]; + + private userSettingsService = inject(UserSettingsService); + private translate = inject(TranslateService); + private clipboard = inject(ClipboardService); + private toast = inject(ToastNotificationService); + private host = inject>(ElementRef); + private injector = inject(Injector); + + private readonly docs = inject(WhiteLabelingService).getDocsUrl(); + + readonly steps: GetStartedStep[] = [ + {key: 'add-device', doc: 'getting-started/1/#step-11-create-a-device', link: '/entities/devices/all', page: 'device.devices'}, + {key: 'send-value', doc: 'getting-started/1/#step-12-verify-device-connectivity', code: sendCommand(25)}, + {key: 'add-dashboard', doc: 'getting-started/2/', link: '/dashboards/all', page: 'dashboard.dashboards'}, + {key: 'add-alarm-rule', doc: 'getting-started/3/#step-31-configure-alarm-rule', link: '/alarms/alarm-rules', + page: 'home.get-started.alarm-rules'}, + {key: 'raise-alarm', doc: 'getting-started/3/#step-32-trigger-an-alarm', code: sendCommand(26)}, + {key: 'share', doc: 'getting-started/4/#step-41-create-a-customer', link: '/customers/all', page: 'customer.customers'} + ]; + + private readonly settings = signal(null); + + readonly loaded = computed(() => this.settings() !== null); + + readonly done = computed(() => Math.min(this.steps.length, Math.max(0, this.settings()?.maxSelectedIndex ?? 0))); + + readonly allDone = computed(() => this.done() >= this.steps.length); + + readonly open = computed(() => { + if (this.allDone()) { + return -1; + } + const last = this.settings()?.lastSelectedIndex; + return last != null && last >= 0 && last < this.steps.length ? last : this.done(); + }); + + readonly progress = computed(() => { + if (!this.loaded() || !this.done()) { + return null; + } + return this.allDone() + ? this.translate.instant('home.get-started.all-done') + : this.translate.instant('home.get-started.progress', {done: this.done(), total: this.steps.length}); + }); + + constructor() { + this.userSettingsService.getGettingStarted({ignoreLoading: true}).subscribe({ + next: settings => this.settings.set({lastSelectedIndex: settings?.lastSelectedIndex ?? 0, maxSelectedIndex: settings?.maxSelectedIndex ?? 0}), + error: () => this.settings.set({lastSelectedIndex: 0, maxSelectedIndex: 0}) + }); + effect(() => { + this.open(); + untracked(() => afterNextRender(() => decorateCodeBlocks(this.host.nativeElement, this.translate, + text => this.clipboard.copyFromContent(text)), {injector: this.injector})); + }); + } + + docUrl(step: GetStartedStep): string { + return this.docs + step.doc; + } + + isDone(index: number): boolean { + return index < this.done(); + } + + select(index: number): void { + if (index !== this.open()) { + this.save({...this.settings(), lastSelectedIndex: index}); + } + } + + toggle(index: number): void { + if (this.isDone(index)) { + this.save({lastSelectedIndex: index, maxSelectedIndex: index}); + } else { + const done = index + 1; + this.save({lastSelectedIndex: done, maxSelectedIndex: Math.max(this.done(), done)}); + } + } + + startOver(): void { + const before = this.settings(); + this.save({lastSelectedIndex: 0, maxSelectedIndex: 0}); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.get-started.started-over'), { + label: this.translate.instant('home.customize.undo'), + action: () => this.save(before) + })); + } + + private save(settings: GettingStarted): void { + this.settings.set(settings); + this.userSettingsService.updateGettingStarted(settings, {ignoreLoading: true}).subscribe(); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html new file mode 100644 index 0000000000..b48969c846 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html @@ -0,0 +1,84 @@ + + + @if (loaded()) { +
+ +
+
+ @for (group of groups; track group.label) { +
{{ group.label | translate }}
+
    + @for (step of group.steps; track step.key) { + @let stepState = state(step); +
  1. +
    + + +
    + @if (open() === step) { +
    +
    + {{ 'home.get-started.step-of' | translate: {step: number(step), total: total} }} + {{ 'home.get-started-sys-admin.' + step.key + '.title' | translate }} +
    +

    {{ 'home.get-started-sys-admin.' + step.key + '.text' | translate }} + {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }} +

    +
    + @if (stepState === 'done') { + + {{ 'home.get-started-sys-admin.' + step.key + '.action' | translate }} + } @else { + + {{ 'home.get-started-sys-admin.' + step.key + '.action' | translate }} + } + + @if (!step.needed && stepState !== 'done') { + + } +
    +
    + } +
  2. + } +
+ } +
+ @if (finished()) { +
+ {{ (doneCount() === total ? 'home.get-started-sys-admin.finished' : 'home.get-started-sys-admin.finished-skipped') + | translate: {count: total - doneCount()} }} + +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss new file mode 100644 index 0000000000..ac4775be5b --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss @@ -0,0 +1,295 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-table'; + +:host { + --tb-home-card-gap: 8px; + --tb-home-card-hideable-top: 20px; + --tb-home-card-hideable-header: 36px; + display: block; + min-width: 0; + container: tb-get-started-sys-admin / inline-size; +} + +.tb-sgs-bar { + height: 4px; + margin-top: -6px; + overflow: hidden; + border-radius: 2px; + background: rgba(0, 0, 0, 0.08); + + > i { + display: block; + height: 100%; + border-radius: 2px; + background: var(--tb-ok, #198038); + } +} + +.tb-sgs-group { + margin: 10px 0 2px; + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.5px; + text-transform: uppercase; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + &:first-child { + margin-top: 0; + } +} + +.tb-sgs-list { + display: grid; + gap: 2px; + margin: 0 -8px; + padding: 0; + list-style: none; + + li { + min-width: 0; + border-radius: 10px; + + &.open { + background: rgba(0, 0, 0, 0.03); + } + } +} + +.tb-sgs-row { + display: flex; + align-items: center; + gap: 10px; + padding: 0 8px; +} + +.tb-sgs-mark { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 22px; + height: 22px; + border: 1px solid var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + border-radius: 50%; + background: #fff; + font: 500 12px/1 var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + color: inherit; + } +} + +li.done .tb-sgs-mark { + border-color: transparent; + background: var(--tb-ok-tint, rgba(25, 128, 56, 0.08)); + color: var(--tb-ok, #198038); +} + +li.skipped .tb-sgs-mark { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-sgs-title { + display: flex; + flex: 1; + align-items: center; + justify-content: space-between; + gap: 8px; + min-width: 0; + height: 36px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + text-align: left; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + cursor: pointer; + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } +} + +.tb-sgs-title-text { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +li.open .tb-sgs-title { + font-weight: 500; +} + +li.done:not(.open) .tb-sgs-title { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-sgs-state { + flex: none; + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-sgs-body { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 8px; + min-width: 0; + padding: 0 12px 8px 40px; + + p { + margin: 0; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } +} + +.tb-sgs-head { + display: none; +} + +.tb-sgs-guide { + border-radius: 4px; + font-weight: 500; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + white-space: nowrap; + color: var(--tb-primary-500); + transition: text-decoration-color .15s ease; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration-color: currentColor; + } + + .mat-icon { + width: 14px; + height: 14px; + margin-left: 2px; + font-size: 14px; + line-height: 14px; + vertical-align: -2px; + } +} + +.tb-sgs-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 8px; +} + +.tb-sgs-spacer { + flex: 1 1 auto; + min-width: 0; +} + +.tb-sgs-action.mdc-button { + height: 32px; + padding: 0 16px; + border-radius: 4px; +} + +.tb-sgs-action.mat-mdc-outlined-button { + background: #fff; +} + +.tb-sgs-skip.mat-mdc-button, .tb-sgs-close.mat-mdc-outlined-button { + height: 32px; +} + +.tb-sgs-skip.mat-mdc-button { + margin-right: -8px; + padding: 0 8px; +} + +.tb-sgs-finish { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-sgs-close.mat-mdc-outlined-button { + flex: none; + padding: 0 16px; + border-radius: 4px; +} + +@container tb-get-started-sys-admin (min-width: 600px) { + .tb-sgs-steps { + position: relative; + padding-right: 54%; + } + + .tb-sgs-body { + position: absolute; + top: 0; + right: 0; + bottom: 0; + display: flex; + flex-direction: column; + gap: 12px; + box-sizing: border-box; + width: calc(54% - 16px); + padding: 14px 16px; + border-radius: 10px; + background: rgba(0, 0, 0, 0.03); + + p { + max-width: 52ch; + font-size: 14px; + line-height: 22px; + letter-spacing: 0.1px; + } + } + + .tb-sgs-head { + display: flex; + flex-direction: column; + gap: 2px; + } + + .tb-sgs-head-n { + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.4px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + .tb-sgs-head-t { + font: 500 16px/24px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-sgs-actions { + margin-top: auto; + padding-top: 4px; + } + + .tb-sgs-action.mdc-button, .tb-sgs-skip.mat-mdc-button { + height: 36px; + } + + li.open .tb-sgs-title-text { + white-space: normal; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts new file mode 100644 index 0000000000..a96d059529 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + signal +} from '@angular/core'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { of } from 'rxjs'; +import { catchError } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; +import { UserSettingsService } from '@core/http/user-settings.service'; +import { WhiteLabelingService } from '@core/http/white-labeling.service'; +import { EntityType } from '@shared/models/entity-type.models'; +import { FeaturesInfo } from '@shared/models/settings.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; + +type SysAdminStepKey = 'tenant' | 'email' | 'sms' | 'wl' | '2fa' | 'oauth' | 'slack'; + +export interface SysAdminStep { + key: SysAdminStepKey; + needed: boolean; + link: string; + queryParams?: Record; + guide: string; + feature?: keyof FeaturesInfo; +} + +const STEPS: SysAdminStep[] = [ + {key: 'tenant', needed: true, link: '/tenants', queryParams: {action: 'add'}, guide: 'user-guide/multi-tenancy/'}, + {key: 'email', needed: true, link: '/settings/outgoing-mail', guide: 'user-guide/ui/mail-settings/', feature: 'emailEnabled'}, + {key: 'sms', needed: false, link: '/settings/notifications', guide: 'user-guide/ui/sms-provider-settings/', feature: 'smsEnabled'}, + {key: 'wl', needed: false, link: '/white-labeling/whiteLabel', guide: 'user-guide/white-labeling/', feature: 'whiteLabelingEnabled'}, + {key: '2fa', needed: false, link: '/security-settings/2fa', guide: 'user-guide/security/two-factor-authentication/', + feature: 'twoFaEnabled'}, + {key: 'oauth', needed: false, link: '/security-settings/oauth2', guide: 'user-guide/security/oauth-2-support/', feature: 'oauthEnabled'}, + {key: 'slack', needed: false, link: '/settings/notifications', guide: 'user-guide/ui/slack-settings/', feature: 'notificationEnabled'} +]; + +const LOADING_HEIGHT = 398; +const HEIGHT_KEY = 'tb-home-get-started-sys-admin-height'; + +const storedHeight = (): number => { + return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT; +}; + +export type StepState = 'done' | 'skipped' | 'todo'; + +@Component({ + selector: 'tb-get-started-sys-admin-home', + templateUrl: './get-started-sys-admin-home.component.html', + styleUrls: ['./get-started-sys-admin-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class GetStartedSysAdminHomeComponent { + + private readonly card = HOME_CARDS[HomeCardId.GET_STARTED_SYS_ADMIN]; + + readonly total = STEPS.length; + + readonly groups = [ + {label: 'home.get-started-sys-admin.before-tenants', steps: STEPS.filter(step => step.needed)}, + {label: 'home.get-started-sys-admin.when-needed', steps: STEPS.filter(step => !step.needed)} + ]; + + private store = inject(Store); + private translate = inject(TranslateService); + private userSettingsService = inject(UserSettingsService); + private readonly docs = inject(WhiteLabelingService).getDocsUrl(); + + private readonly tenants = signal(null); + private readonly features = signal(null); + private readonly skipped = signal(null); + private readonly selected = signal(null); + + readonly loaded = computed(() => this.tenants() !== null && this.features() !== null && this.skipped() !== null); + + readonly cardDefinition = computed(() => this.loaded() ? this.card : {...this.card, height: storedHeight()}); + + readonly states = computed>(() => { + const features = this.features(); + const skipped = this.skipped() ?? []; + return Object.fromEntries(STEPS.map(step => { + const done = step.key === 'tenant' ? !!this.tenants() : !!features?.[step.feature]; + let state: StepState = 'todo'; + if (done) { + state = 'done'; + } else if (!step.needed && skipped.includes(step.key)) { + state = 'skipped'; + } + return [step.key, state]; + })) as Record; + }); + + readonly doneCount = computed(() => STEPS.filter(step => this.states()[step.key] === 'done').length); + + readonly progress = computed(() => this.doneCount() + ? this.translate.instant('home.get-started-sys-admin.progress', {done: this.doneCount(), total: STEPS.length}) : null); + + readonly finished = computed(() => this.loaded() && STEPS.every(step => ['done', 'skipped'].includes(this.states()[step.key]))); + + readonly open = computed(() => { + const selected = this.selected(); + if (selected === '-') { + return null; + } + return STEPS.find(step => step.key === selected) ?? STEPS.find(step => this.states()[step.key] === 'todo') ?? null; + }); + + readonly tenantCount = computed(() => this.tenants() ?? 0); + + constructor() { + const config = {ignoreErrors: true, ignoreLoading: true}; + inject(SysAdminHomeService).featuresInfo$.subscribe(features => this.features.set(features ?? {} as FeaturesInfo)); + this.userSettingsService.getGettingStarted(config).pipe(catchError(() => of(null))) + .subscribe(settings => this.skipped.set(settings?.skipped ?? [])); + const destroyRef = inject(DestroyRef); + inject(HomeCountService).watchEntityCount(EntityType.TENANT, count => this.tenants.set(count), destroyRef); + const host = inject>(ElementRef); + const observer = new ResizeObserver(() => this.rememberHeight(host.nativeElement)); + observer.observe(host.nativeElement); + destroyRef.onDestroy(() => { + observer.disconnect(); + }); + } + + state(step: SysAdminStep): StepState { + return this.states()[step.key]; + } + + number(step: SysAdminStep): number { + return STEPS.indexOf(step) + 1; + } + + docUrl(step: SysAdminStep): string { + return this.docs + step.guide; + } + + toggle(step: SysAdminStep): void { + this.selected.set(this.open() === step ? '-' : step.key); + } + + skip(step: SysAdminStep): void { + const skipped = this.skipped() ?? []; + const next = skipped.includes(step.key) ? skipped.filter(key => key !== step.key) : [...skipped, step.key]; + this.skipped.set(next); + this.selected.set(null); + this.userSettingsService.updateGettingStarted({skipped: next}).subscribe(); + } + + private rememberHeight(element: HTMLElement): void { + const height = Math.round(element.getBoundingClientRect().height); + if (!this.loaded() || !height) { + return; + } + writeStored(HEIGHT_KEY, String(height)); + } + + close(): void { + this.store.dispatch(new ActionPreferencesUpdateHomeCards({[HomeCardId.GET_STARTED_SYS_ADMIN]: false})); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.scss new file mode 100644 index 0000000000..d6d496d07f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.scss @@ -0,0 +1,167 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-home-card { + position: relative; + display: flex; + flex-direction: column; + gap: var(--tb-home-card-gap, 12px); + box-sizing: border-box; + min-width: 0; + padding: var(--tb-home-card-padding, 20px); + border-radius: 12px; + background: var(--tb-surface, #fff); + box-shadow: var(--tb-home-card-shadow); +} + +.tb-home-card-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px 12px; + min-height: var(--tb-home-card-header-height, 36px); + flex-wrap: wrap; +} + +.tb-home-card-title-group { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.tb-home-card-title { + &:hover, &:focus, &:active { + border-bottom: none; + } + + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + overflow: hidden; + font: 600 16px/24px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.15px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + text-decoration: none; + border-bottom: none; + + &.link::after { + content: 'chevron_right'; + display: inline-block; + margin-left: -2px; + font-family: 'Material Icons'; + font-size: 20px; + font-weight: normal; + line-height: 1; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &.link:hover { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + &::after { + color: inherit; + } + } + + &.link:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 4px; + } +} + +.tb-home-card-count { + margin-left: 2px; + font-weight: 500; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.54)); + font-variant-numeric: tabular-nums; +} + +.tb-home-card-icon { + flex: none; + margin-right: 2px; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-home-card-actions { + display: flex; + flex-wrap: nowrap; + align-items: center; + gap: 4px; + min-width: 0; + margin-left: auto; + + &:empty { + display: none; + } +} + +.tb-home-card.hideable { + padding-top: var(--tb-home-card-hideable-top, 16px); + + .tb-home-card-header { + min-height: var(--tb-home-card-hideable-header, 32px); + flex-wrap: nowrap; + } +} + +.tb-home-card-header.expanded .tb-home-card-actions { + flex: 1; + justify-content: flex-end; +} + +.tb-home-card-hide.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } + + &:hover, &:focus-visible { + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +@media (hover: hover) { + .tb-home-card-hide.mat-mdc-icon-button.mat-mdc-button-base { + opacity: 0; + transition: opacity .15s, color .15s; + } + + .tb-home-card:is(:hover, :focus-within) .tb-home-card-hide.mat-mdc-icon-button.mat-mdc-button-base { + opacity: 1; + } +} + +@media (hover: hover) and (prefers-reduced-motion: reduce) { + .tb-home-card-hide.mat-mdc-icon-button.mat-mdc-button-base { + transition: none; + } +} + +@media (max-width: 599px) { + .tb-home-card.hideable { + padding-top: var(--tb-home-card-padding, 20px); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts new file mode 100644 index 0000000000..c970bf9efa --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { TranslateService } from '@ngx-translate/core'; +import { AppState } from '@core/core.state'; +import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; +import { homeToast } from '@home/pages/home-page/home-list.models'; +import { HomeCardDefinition } from '@home/pages/home-page/home-cards.models'; + +@Component({ + selector: 'tb-home-card', + template: ` +
+
+
+ @if (card().link) { + + {{ card().icon }} + {{ card().name | translate }} + @if (count()) { + {{ count() | shortNumber }} + } + + } @else { + + {{ card().icon }} + {{ card().name | translate }} + @if (countText()) { + {{ countText() }} + } + + } + +
+
+ @if (hideable() && !expanded()) { + + } + +
+
+ +
+ `, + styleUrls: ['./home-card.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HomeCardComponent { + + card = input.required(); + + hideable = input(false); + + expanded = input(false); + + count = input(null); + + countText = input(null); + + private store = inject(Store); + private translate = inject(TranslateService); + private toast = inject(ToastNotificationService); + + hide(): void { + const id = this.card().id; + const name = this.translate.instant(this.card().name); + this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: false})); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.customize.hidden', {name}), { + label: this.translate.instant('home.customize.undo'), + action: () => this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: true})) + })); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.scss new file mode 100644 index 0000000000..867b3e1e0c --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.scss @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; +} + +.tb-home-foot { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 16px; + margin-top: 8px; + padding: 12px 0 0; + border-top: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05)); +} + +.tb-hidden-cards { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 2px; + min-width: 0; +} + +.tb-hidden-lbl { + margin: 0 6px 0 4px; + font: 400 13px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-foot-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 32px; + padding: 0 10px 0 8px; + border: 0; + border-radius: 8px; + background: none; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + &:hover { + background: rgba(0, 0, 0, 0.04); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + .mat-icon { + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: -2px; + } +} + +.tb-customize-btn { + margin-left: auto; +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.ts new file mode 100644 index 0000000000..a6f311e9c7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-cards-footer.component.ts @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { MatDialog } from '@angular/material/dialog'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectHomeCards } from '@core/auth/auth.selectors'; +import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS, isHomeCardShown } from '@home/pages/home-page/home-cards.models'; +import { + CustomizeHomeDialogComponent, + CustomizeHomeDialogData +} from '@home/pages/home-page/components/customize-home-dialog.component'; + +@Component({ + selector: 'tb-home-cards-footer', + template: ` +
+ @if (hidden().length) { +
+ {{ 'home.customize.show-on-home' | translate }} + @for (card of hidden(); track card.id) { + + } +
+ } + +
+ `, + styleUrls: ['./home-cards-footer.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HomeCardsFooterComponent { + + cards = input.required(); + + private store = inject(Store); + private dialog = inject(MatDialog); + + private settings = toSignal(this.store.select(selectHomeCards), {initialValue: {}}); + + readonly hidden = computed(() => this.cards().filter(id => !isHomeCardShown(this.settings(), id)).map(id => HOME_CARDS[id])); + + show(id: HomeCardId): void { + this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: true})); + setTimeout(() => document.querySelector(`[data-home-card="${id}"]`)?.scrollIntoView({behavior: 'smooth', block: 'center'})); + } + + customize(): void { + this.dialog.open(CustomizeHomeDialogComponent, { + panelClass: 'tb-customize-home-panel', + autoFocus: 'first-tabbable', + data: {cards: this.cards()} + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.scss new file mode 100644 index 0000000000..05b71c6228 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.scss @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +tb-home-hscroll { + display: block; + min-width: 0; +} + +.tb-hscroll { + margin: 0 -20px; + + .tb-hscroll-view { + position: relative; + + &::before, &::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + z-index: 1; + width: 56px; + pointer-events: none; + transition: opacity .15s ease; + } + + &::before { + left: 0; + background: linear-gradient(90deg, var(--tb-surface, #fff), transparent); + } + + &::after { + right: 0; + background: linear-gradient(270deg, var(--tb-surface, #fff), transparent); + } + } + + &.at-start .tb-hscroll-view::before, &.at-end .tb-hscroll-view::after { + opacity: 0; + } + + .tb-hscroll-track { + position: relative; + display: flex; + gap: 12px; + overflow-x: auto; + padding: 2px 20px; + scroll-padding: 0 20px; + scroll-snap-type: x proximity; + overscroll-behavior-x: contain; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + + > * { + flex: none; + scroll-snap-align: start; + } + + @media (prefers-reduced-motion: no-preference) { + scroll-behavior: smooth; + } + } + + &.dragging .tb-hscroll-track { + scroll-behavior: auto; + scroll-snap-type: none; + } + + .tb-hscroll-btn { + position: absolute; + top: var(--arrow-y, 50%); + z-index: 2; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 50%; + background: var(--tb-surface, #fff); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.14), 0 4px 14px rgba(16, 24, 40, 0.2); + cursor: pointer; + opacity: 0; + pointer-events: none; + transform: translateY(-50%); + transition: opacity .15s ease; + + &:hover { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.16), 0 6px 18px rgba(16, 24, 40, 0.26); + } + + &.prev { + left: 10px; + } + + &.next { + right: 10px; + } + + .mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + } + } + + &:hover .tb-hscroll-btn { + opacity: 1; + pointer-events: auto; + } + + &.at-start .tb-hscroll-btn.prev, &.at-end .tb-hscroll-btn.next { + opacity: 0; + pointer-events: none; + } + + .tb-hscroll-bar { + position: relative; + height: 12px; + margin: 2px 20px -4px; + cursor: pointer; + touch-action: none; + opacity: 0; + transition: opacity .15s ease; + + > i { + position: absolute; + top: 4px; + left: 0; + height: 4px; + border-radius: 2px; + background: var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + transition: background-color .15s ease; + } + + &:hover > i { + background: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + } + + &:hover .tb-hscroll-bar, &.dragging .tb-hscroll-bar { + opacity: 1; + } + + &.dragging .tb-hscroll-bar > i { + background: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &.fits .tb-hscroll-bar { + visibility: hidden; + } + + @media (hover: none) { + .tb-hscroll-btn, .tb-hscroll-bar { + display: none; + } + + .tb-hscroll-view::before, .tb-hscroll-view::after { + width: 24px; + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.ts new file mode 100644 index 0000000000..1f46148992 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-hscroll.component.ts @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + DestroyRef, + ElementRef, + inject, + input, + signal, + ViewChild, + ViewEncapsulation +} from '@angular/core'; + +const MIN_THUMB = 32; + +@Component({ + selector: 'tb-home-hscroll', + template: ` +
+
+
+ +
+ + +
+ +
+ `, + styleUrls: ['./home-hscroll.component.scss'], + encapsulation: ViewEncapsulation.None, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HomeHscrollComponent implements AfterViewInit { + + label = input(); + + @ViewChild('track', {static: true}) trackRef: ElementRef; + @ViewChild('bar', {static: true}) barRef: ElementRef; + + readonly atStart = signal(true); + readonly atEnd = signal(false); + readonly fits = signal(false); + readonly dragging = signal(false); + readonly thumbWidth = signal(MIN_THUMB); + readonly thumbX = signal(0); + readonly arrowY = signal(null); + + private destroyRef = inject(DestroyRef); + + ngAfterViewInit(): void { + const observer = new ResizeObserver(() => this.layout()); + observer.observe(this.trackRef.nativeElement); + const mutations = new MutationObserver(() => this.layout()); + mutations.observe(this.trackRef.nativeElement, {childList: true, subtree: true}); + this.destroyRef.onDestroy(() => { + observer.disconnect(); + mutations.disconnect(); + }); + this.layout(); + } + + sync(): void { + const track = this.trackRef.nativeElement; + const width = track.clientWidth; + const max = track.scrollWidth - width; + const x = track.scrollLeft; + const rail = this.barRef.nativeElement.clientWidth; + this.atStart.set(x < 2); + this.atEnd.set(x > max - 2); + this.fits.set(max < 2); + const thumb = Math.max(MIN_THUMB, rail * width / Math.max(1, track.scrollWidth)); + this.thumbWidth.set(thumb); + this.thumbX.set(max > 0 ? (x / max) * (rail - thumb) : 0); + } + + step(dir: number): void { + const track = this.trackRef.nativeElement; + const pad = parseFloat(getComputedStyle(track).paddingLeft) || 0; + const left = track.scrollLeft; + const right = left + track.clientWidth; + const kids = Array.from(track.children) as HTMLElement[]; + const next = dir > 0 + ? kids.find(kid => kid.offsetLeft + kid.offsetWidth > right - pad + 1) + : kids.reverse().find(kid => kid.offsetLeft < left + pad - 1); + if (next) { + track.scrollTo({left: dir > 0 ? next.offsetLeft - pad : next.offsetLeft + next.offsetWidth + pad - track.clientWidth}); + } + } + + press(event: PointerEvent): void { + event.preventDefault(); + const bar = this.barRef.nativeElement; + const track = this.trackRef.nativeElement; + bar.setPointerCapture(event.pointerId); + this.dragging.set(true); + const move = (moveEvent: PointerEvent) => { + const rect = bar.getBoundingClientRect(); + const thumb = this.thumbWidth(); + const share = Math.min(1, Math.max(0, (moveEvent.clientX - rect.left - thumb / 2) / Math.max(1, rect.width - thumb))); + track.scrollLeft = share * (track.scrollWidth - track.clientWidth); + }; + const end = () => { + bar.removeEventListener('pointermove', move); + this.dragging.set(false); + }; + bar.addEventListener('pointermove', move); + bar.addEventListener('pointerup', end, {once: true}); + bar.addEventListener('pointercancel', end, {once: true}); + move(event); + } + + private layout(): void { + const view = this.trackRef.nativeElement.parentElement; + const picture = (this.trackRef.nativeElement.querySelector('[data-hscroll-anchor]') ?? this.trackRef.nativeElement.firstElementChild) as HTMLElement; + if (view && picture) { + const rect = picture.getBoundingClientRect(); + if (rect.height) { + this.arrowY.set(rect.top + rect.height / 2 - view.getBoundingClientRect().top); + } + } + this.sync(); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.scss new file mode 100644 index 0000000000..d728472202 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.scss @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; +} + +.tb-home-list-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + min-height: 36px; + padding-top: 8px; + border-top: 1px solid rgba(0, 0, 0, 0.05); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-home-list-toggle.mat-mdc-button { + margin-left: -8px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-home-list-spacer { + flex: 1 1 auto; +} + +.tb-home-list-count { + font-variant-numeric: tabular-nums; +} + +.tb-home-list-view-all { + display: inline-flex; + align-items: center; + height: 36px; + margin-right: -8px; + padding: 0 4px 0 8px; + border-radius: 4px; + font-weight: 500; + font-size: 14px; + letter-spacing: 0.03125em; + white-space: nowrap; + text-decoration: none; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + transition: background-color .15s ease; + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } + + &:hover { + background: rgba(0, 0, 0, 0.04); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: -2px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts new file mode 100644 index 0000000000..4ae2813187 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-list-footer.component.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core'; +import { Params } from '@angular/router'; +import { HOME_LIST_LIMIT, HOME_LIST_PREVIEW, HOME_LIST_SLACK } from '@home/pages/home-page/home-list.models'; + +@Component({ + selector: 'tb-home-list-footer', + template: ` + @if (!few() || (total() && link())) { + + } + `, + styleUrls: ['./home-list-footer.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HomeListFooterComponent { + + total = input(0); + + expanded = input(false); + + link = input(null); + + params = input(null); + + preview = input(HOME_LIST_PREVIEW); + + slack = input(HOME_LIST_SLACK); + + limit = input(HOME_LIST_LIMIT); + + scroll = input(false); + + expandedChange = output(); + + readonly few = computed(() => this.total() <= this.preview() + this.slack()); + + readonly shown = computed(() => { + const total = this.total(); + if (this.few()) { + return total; + } + if (this.expanded()) { + return this.scroll() ? total : Math.min(total, this.limit()); + } + return this.preview(); + }); + + readonly toggleLabel = computed(() => { + if (this.expanded()) { + return 'home.list.show-less'; + } + return this.total() <= this.limit() ? 'home.list.show-all' : 'home.list.show-more'; + }); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss new file mode 100644 index 0000000000..e19adf59c1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-menu.scss @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.mat-mdc-menu-panel.tb-alarms-home-menu { + &.mat-menu-below { + margin-top: 4px; + } + + &.mat-menu-above { + margin-bottom: 4px; + } +} + +.tb-system-tooltip .mdc-tooltip__surface { + white-space: pre-line; +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss new file mode 100644 index 0000000000..76b917af59 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.mat-mdc-snack-bar-container.tb-home-toast.tb-home-toast { + .tb-toast.tb-toast.tb-toast { + gap: 4px; + box-sizing: border-box; + max-width: min(480px, calc(100vw - 16px)); + margin: 8px; + padding: 6px 6px 6px 16px; + border-radius: 4px; + background: #323232; + box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2), 0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: .25px; + color: rgba(255, 255, 255, 0.92); + } + + .tb-toast .toast-text.toast-text { + flex: 1 1 auto; + min-width: 0; + padding: 4px 8px 4px 0; + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + .tb-toast .mat-mdc-button.mat-mdc-button-base.mat-mdc-button-base { + --mat-button-text-label-text-color: rgba(255, 255, 255, 0.92); + flex: none; + min-width: 0; + height: 32px; + margin: 0; + padding: 0 10px; + border-radius: 4px; + font: 500 14px/32px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.03125em; + color: rgba(255, 255, 255, 0.92); + + &:hover { + background: rgba(255, 255, 255, 0.08); + } + + &:focus-visible { + outline: 2px solid #fff; + outline-offset: -2px; + } + } + + .mdc-snackbar__surface.mdc-snackbar__surface { + min-width: 0; + padding: 0; + } + + &.mat-snack-bar-container-animations-enabled { + &.mat-snack-bar-container-enter { + animation-duration: 1ms; + + .mdc-snackbar__surface { + animation: tb-home-toast-in .2s ease both; + } + } + + &.mat-snack-bar-container-exit { + animation-duration: .2s; + animation-timing-function: ease; + + .mdc-snackbar__surface { + animation: tb-home-toast-out .2s ease both; + } + } + } + + @media (prefers-reduced-motion: reduce) { + &.mat-snack-bar-container-animations-enabled .mdc-snackbar__surface { + animation: none; + } + } +} + +@keyframes tb-home-toast-in { + from { + opacity: 0; + transform: translateY(16px); + } +} + +@keyframes tb-home-toast-out { + to { + opacity: 0; + transform: translateY(16px); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.scss new file mode 100644 index 0000000000..4c6899afba --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.scss @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: inline-flex; + max-width: 100%; +} + +.tb-home-toggle { + display: inline-flex; + box-sizing: border-box; + height: 32px; + max-width: 100%; + padding: 2px; + border-radius: 100px; + background: rgba(0, 0, 0, 0.06); +} + +.tb-home-toggle-option { + flex: 1 1 auto; + height: 28px; + margin: 0; + padding: 0 12px; + border: 1px solid transparent; + border-radius: 20px; + background: none; + font: 400 14px/26px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + cursor: pointer; + + &[aria-pressed="true"] { + background: #fff; + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.10), 0 1px 4px rgba(16, 24, 40, 0.06); + font-weight: 500; + line-height: 24px; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: -2px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.ts new file mode 100644 index 0000000000..b214616a03 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toggle.component.ts @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'; + +export interface HomeToggleOption { + value: T; + label: string; +} + +@Component({ + selector: 'tb-home-toggle', + template: ` +
+ @for (option of options(); track option.value) { + + } +
+ `, + styleUrls: ['./home-toggle.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HomeToggleComponent { + + options = input.required[]>(); + + value = input.required(); + + label = input(); + + valueChange = output(); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html new file mode 100644 index 0000000000..ce5c790bac --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html @@ -0,0 +1,47 @@ + + + + + add{{ 'home.install.add-tenant' | translate }} + + +
+ @for (item of counts; track item.entityType) { + @let count = item.count(); + @if (item.link && count) { + + {{ item.label | translate }} + {{ count | shortNumber }} + + } @else { +
+ {{ item.label | translate }} + {{ count === null ? '–' : (count | shortNumber) }} +
+ } + } +
+ @if (withFeatures()) { +
+ {{ 'home.install.features' | translate }} + @if (loaded()) { + {{ 'home.install.features-count' | translate: {on: configured(), total: features().length} }} + } +
+ + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.scss new file mode 100644 index 0000000000..c9fe1301f7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.scss @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; +@use './home-table'; + +:host { + display: block; + min-width: 0; + container: tb-install-home / inline-size; +} + +.tb-install-add.mat-mdc-button { + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + .mat-icon { + margin-right: 6px; + } +} + +.tb-install-counts { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + + .tb-home-tile.tb-home-tile { + width: auto; + max-width: none; + height: 60px; + padding: 5px 10px; + text-decoration: none; + + &, &:hover, &:focus, &:active { + border-bottom-style: solid; + } + + &.static { + cursor: default; + + &:hover { + border-color: rgba(0, 0, 0, 0.10); + } + } + + &.zero { + border-style: dashed; + background: transparent; + + &:hover { + border-style: dashed; + } + + .tb-home-tile-label { + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + } + } +} + +@container tb-install-home (max-width: 440px) { + .tb-install-counts { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +.tb-install-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + margin-top: 4px; + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.5px; + text-transform: uppercase; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-install-head-count { + letter-spacing: 0.25px; + text-transform: none; + font-variant-numeric: tabular-nums; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-install-features { + display: grid; + grid-template-columns: minmax(0, 1fr); + margin: 0 -8px; +} + +.tb-install-feature { + display: flex; + align-items: center; + gap: 12px; + box-sizing: border-box; + min-width: 0; + height: 40px; + padding: 0 8px; + border: none; + border-radius: 6px; + text-decoration: none; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + &:hover { + border: none; + background: rgba(0, 0, 0, 0.04); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: -2px; + } +} + +.tb-install-feature-icon.mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.tb-install-feature.pending .tb-install-feature-icon.mat-icon { + color: var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + animation: tb-install-pending 1.2s ease-in-out infinite alternate; +} + +@keyframes tb-install-pending { + from { + opacity: 1; + } + to { + opacity: 0.4; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-install-feature.pending .tb-install-feature-icon.mat-icon { + animation: none; + } +} + +.tb-install-feature.on .tb-install-feature-icon.mat-icon { + color: var(--tb-primary-500); +} + +.tb-install-feature-text { + min-width: 0; + overflow: hidden; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-overflow: ellipsis; +} + +@container tb-install-home (min-width: 260px) { + .tb-install-features { + grid-template-columns: repeat(2, minmax(0, 1fr)); + column-gap: 12px; + clip-path: inset(1px -8px 0 -8px); + + > .tb-install-feature { + position: relative; + + &::before { + content: ""; + position: absolute; + top: 0; + right: 8px; + left: 8px; + border-top: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05)); + pointer-events: none; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts new file mode 100644 index 0000000000..1420b32d6b --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, signal, WritableSignal } from '@angular/core'; +import { EntityType } from '@shared/models/entity-type.models'; +import { FeaturesInfo } from '@shared/models/settings.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; + +interface InstallCount { + label: string; + entityType: EntityType; + link?: string; + count: WritableSignal; +} + +interface InstallFeature { + label: string; + key: keyof FeaturesInfo; + link: string; +} + +const FEATURES: InstallFeature[] = [ + {label: 'home.install.white-labeling', key: 'whiteLabelingEnabled', link: '/white-labeling/whiteLabel'}, + {label: 'home.install.mail-server', key: 'emailEnabled', link: '/settings/outgoing-mail'}, + {label: 'home.install.sms-provider', key: 'smsEnabled', link: '/settings/notifications'}, + {label: 'home.install.slack', key: 'notificationEnabled', link: '/settings/notifications'}, + {label: 'home.install.oauth', key: 'oauthEnabled', link: '/security-settings/oauth2'}, + {label: 'home.install.two-fa', key: 'twoFaEnabled', link: '/security-settings/2fa'} +]; + +@Component({ + selector: 'tb-install-items-home', + templateUrl: './install-items-home.component.html', + styleUrls: ['./install-items-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class InstallItemsHomeComponent { + + withFeatures = input(true); + + readonly card = HOME_CARDS[HomeCardId.INSTALL_ITEMS]; + + readonly counts: InstallCount[] = [ + {label: 'home.install.tenants', entityType: EntityType.TENANT, link: '/tenants', count: signal(null)}, + {label: 'home.install.tenant-profiles', entityType: EntityType.TENANT_PROFILE, link: '/tenantProfiles', count: signal(null)}, + {label: 'home.install.users', entityType: EntityType.USER, count: signal(null)}, + {label: 'home.install.customers', entityType: EntityType.CUSTOMER, count: signal(null)}, + {label: 'home.install.dashboards', entityType: EntityType.DASHBOARD, count: signal(null)}, + {label: 'home.install.integrations', entityType: EntityType.INTEGRATION, count: signal(null)} + ]; + + private readonly featuresInfo = signal(null); + + readonly features = computed(() => { + const info = this.featuresInfo(); + return FEATURES.map(feature => ({...feature, on: info ? !!info[feature.key] : null})); + }); + + readonly loaded = computed(() => !!this.featuresInfo()); + + readonly configured = computed(() => this.features().filter(feature => feature.on).length); + + constructor() { + inject(SysAdminHomeService).featuresInfo$.subscribe(info => this.featuresInfo.set(info)); + const homeCounts = inject(HomeCountService); + const destroyRef = inject(DestroyRef); + this.counts.forEach(item => homeCounts.watchEntityCount(item.entityType, count => item.count.set(count), destroyRef)); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.html new file mode 100644 index 0000000000..a0fc3678a2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.html @@ -0,0 +1,124 @@ + + + + @if (searching()) { + + } @else { + + } + + @if (failed()) { +

{{ 'home.iot-hub.unavailable' | translate }}

+ } @else { +
+ {{ 'home.iot-hub.templates' | translate }} + + @for (tile of templates(); track tile.item.id; let first = $first) { + + } @empty { + @if (!loaded()) { + @for (n of skeleton; track n) { + + } + } + } + +
+
+ {{ 'home.iot-hub.device-library' | translate }} + + @for (tile of devices(); track tile.item.id) { + + } + @empty { + @if (!loaded()) { + @for (n of skeleton; track n) { + + } + } + } + @if (deviceTotal()) { + + } + +
+ } +
+
{{ 'home.iot-hub.also' | translate }}
+ +
+
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.scss new file mode 100644 index 0000000000..015f9a29b6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.scss @@ -0,0 +1,421 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-iot-hub-row { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.tb-iot-hub-row-title { + align-self: flex-start; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: .1px; + color: var(--tb-ink-60, rgba(0, 0, 0, 0.6)); + text-decoration: none; + border-bottom: none; + + &:not(.plain)::after { + content: 'chevron_right'; + display: inline-block; + margin-left: -2px; + font-family: 'Material Icons'; + font-size: 18px; + font-weight: normal; + line-height: 1; + vertical-align: bottom; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &:not(.plain):hover, &:not(.plain):focus, &:not(.plain):active { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + border-bottom: none; + + &::after { + color: inherit; + } + } +} + +.tb-iot-hub-card { + display: flex; + flex-direction: column; + gap: 6px; + width: 224px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + font: inherit; + text-align: left; + cursor: pointer; + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + &.placeholder { + cursor: default; + } +} + +.tb-iot-hub-skeleton { + background: linear-gradient(90deg, rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.09) 50%, rgba(0, 0, 0, 0.05) 100%) 0 0 / 200% 100%; + animation: tb-iot-hub-shimmer 1.4s ease-in-out infinite; +} + +.tb-iot-hub-skeleton-line { + display: block; + border-radius: 4px; + + &.name { + width: 62%; + height: 12px; + margin: 3px 0; + } + + &.meta { + width: 38%; + height: 10px; + margin: 3px 0; + } +} + +@keyframes tb-iot-hub-shimmer { + from { + background-position: 100% 0; + } + to { + background-position: -100% 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-iot-hub-skeleton { + animation: none; + } +} + +.tb-iot-hub-card-image { + position: relative; + display: flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 100%; + aspect-ratio: 16 / 10; + padding: 14px; + border-radius: 10px; + + img { + display: block; + width: 100%; + height: auto; + border-radius: 4px; + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.08), 0 6px 16px rgba(16, 24, 40, 0.14); + opacity: 0; + transition: transform .2s ease, opacity .25s ease; + + &.loaded { + opacity: 1; + } + } +} + +@media (prefers-reduced-motion: no-preference) { + .tb-iot-hub-card:hover .tb-iot-hub-card-image img { + transform: translateY(-2px); + } +} + +.tb-iot-hub-card-installed.mat-icon { + position: absolute; + top: 8px; + right: 8px; + width: 18px; + height: 18px; + overflow: visible; + font-size: 18px; + color: #10181d; + background: radial-gradient(circle closest-side, #86e8a6 70%, transparent 72%); +} + +.tb-iot-hub-card-label { + display: flex; + flex-direction: column; + align-items: flex-start; + min-width: 0; + padding: 0 2px; +} + +.tb-iot-hub-card-name { + max-width: 100%; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 500 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-iot-hub-card-meta { + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} + +.tb-iot-hub-device { + display: flex; + align-items: center; + gap: 10px; + box-sizing: border-box; + width: 228px; + padding: 8px 12px 8px 8px; + border: 1px solid var(--tb-line, rgba(0, 0, 0, 0.12)); + border-radius: 8px; + background: none; + font: inherit; + text-align: left; + cursor: pointer; + transition: border-color .15s ease; + + &:hover { + border-color: rgba(0, 0, 0, 0.2); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + &.placeholder { + cursor: default; + + .tb-iot-hub-device-text { + flex: 1; + } + + .tb-iot-hub-skeleton-line.name { + width: 80%; + } + + .tb-iot-hub-skeleton-line.meta { + width: 50%; + } + } +} + +.tb-iot-hub-device-thumb { + position: relative; + flex: none; + width: 48px; + height: 48px; + overflow: hidden; + border-radius: 6px; + + img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: contain; + background: #fff; + opacity: 0; + transition: opacity .25s ease; + + &.loaded { + opacity: 1; + } + } +} + +.tb-iot-hub-all .tb-iot-hub-device-thumb { + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.04); + color: var(--tb-ink-60, rgba(0, 0, 0, 0.6)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.tb-iot-hub-device-text { + display: flex; + flex-direction: column; + min-width: 0; + + b { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 500 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + small { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } +} + +.tb-iot-hub-kinds { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.tb-iot-hub-kind { + display: flex; + align-items: center; + gap: 6px; + box-sizing: border-box; + height: 32px; + padding: 0 14px 0 10px; + border: 1px solid var(--tb-line, rgba(0, 0, 0, 0.12)); + border-radius: 16px; + background: var(--tb-surface, #fff); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + text-decoration: none; + transition: background-color .15s ease, border-color .15s ease; + + &:hover, &:focus, &:active { + border-bottom: 1px solid var(--tb-line, rgba(0, 0, 0, 0.12)); + } + + &:hover { + background: rgba(0, 0, 0, 0.04); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.tb-iot-hub-unavailable { + margin: 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-iot-hub-find.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-ink-60, rgba(0, 0, 0, 0.6)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.tb-iot-hub-search { + display: flex; + flex: 1; + align-items: center; + gap: 4px; + box-sizing: border-box; + min-width: 0; + max-width: 380px; + height: 32px; + padding: 0 2px 0 10px; + border: 1px solid var(--tb-line, rgba(0, 0, 0, 0.12)); + border-radius: 8px; + background: var(--tb-surface, #fff); + + &:focus-within { + border-color: var(--tb-primary-500); + } + + > .mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + .tb-search-input { + flex: 1; + min-width: 0; + margin-left: 2px; + padding: 0; + border: 0; + outline: 0; + background: transparent; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + &::-webkit-search-cancel-button { + display: none; + } + } + + .mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 28px; + --mat-icon-button-state-layer-size: 28px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border-radius: 8px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; + } + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } + } + + .tb-search-clear { + display: none !important; + } + + &.has-text { + .tb-search-clear { + display: inline-flex !important; + } + + .tb-search-go { + background: var(--tb-primary-500); + color: var(--tb-primary-contrast-500, #fff); + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts new file mode 100644 index 0000000000..5e5be732b8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, signal, ViewChild } from '@angular/core'; +import { Router } from '@angular/router'; +import { forkJoin } from 'rxjs'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; +import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { writeStored } from '@core/local-storage/stored'; +import { PageLink } from '@shared/models/page/page-link'; + +const SHOWN = 8; + +const SKELETON_TILES = 6; + +const CACHE_KEY = 'tb-home-iot-hub'; + +const CACHE_TTL_MS = 24 * 60 * 60 * 1000; + +interface HubSnapshot { + at: number; + templates: MpItemVersionView[]; + devices: MpItemVersionView[]; + deviceTotal: number; +} + +let lastSnapshot: HubSnapshot | null = null; + +const readSnapshot = (): HubSnapshot | null => { + if (lastSnapshot) { + return lastSnapshot; + } + try { + const snapshot: HubSnapshot = JSON.parse(localStorage.getItem(CACHE_KEY)); + return snapshot?.at && Date.now() - snapshot.at < CACHE_TTL_MS ? snapshot : null; + } catch { + return null; + } +}; + +const writeSnapshot = (snapshot: HubSnapshot): void => { + lastSnapshot = snapshot; + writeStored(CACHE_KEY, JSON.stringify(snapshot)); +}; + +const TEMPLATE_TINTS = ['#e0f2f1,#80cbc4', '#e3f2fd,#90caf9', '#fff3e0,#ffcc80', '#f3e5f5,#ce93d8', '#e8f5e9,#a5d6a7', + '#e0f7fa,#80deea', '#fbe9e7,#ffab91', '#ede7f6,#b39ddb']; + +const DEVICE_TINTS = ['#eceff1,#b0bec5', '#fbe9e7,#ffab91', '#e0f7fa,#80deea', '#fffde7,#fff59d', '#efebe9,#bcaaa4', + '#ede7f6,#b39ddb', '#e8f5e9,#a5d6a7', '#e3f2fd,#90caf9']; + +export interface IotHubKind { + type: ItemType; + name: string; + icon: string; + route: string; +} + +const KINDS: IotHubKind[] = [ + {type: ItemType.WIDGET, name: 'home.iot-hub.widgets', icon: 'widgets', route: 'widgets'}, + {type: ItemType.CALCULATED_FIELD, name: 'home.iot-hub.calculated-fields', icon: 'functions', route: 'calculated-fields'}, + {type: ItemType.ALARM_RULE, name: 'home.iot-hub.alarm-rules', icon: 'notification_important', route: 'alarm-rules'}, + {type: ItemType.RULE_CHAIN, name: 'home.iot-hub.rule-chains', icon: 'account_tree', route: 'rule-chains'} +]; + +interface HubTile { + item: MpItemVersionView; + tint: string; + image: string | null; + meta: string; +} + +@Component({ + selector: 'tb-iot-hub-home', + templateUrl: './iot-hub-home.component.html', + styleUrls: ['./iot-hub-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class IoTHubHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.IOT_HUB]; + + readonly kinds = KINDS; + + readonly skeleton = Array.from({length: SKELETON_TILES}, (_, i) => i); + + readonly templates = signal([]); + readonly devices = signal([]); + readonly deviceTotal = signal(0); + readonly loaded = signal(false); + readonly failed = signal(false); + readonly searching = signal(false); + readonly query = signal(''); + + @ViewChild('searchInput') searchInput: ElementRef; + @ViewChild('searchOpener', {read: ElementRef}) searchOpener: ElementRef; + + private router = inject(Router); + private api = inject(IotHubApiService); + private actions = inject(IotHubActionsService); + + private installedTemplates: IotHubInstalledItem[] = []; + private installedDeviceCounts: Record = {}; + + constructor() { + this.load(); + } + + isInstalled(item: MpItemVersionView): boolean { + return this.installedTemplates.some(installed => installed.itemId === item.itemId); + } + + open(item: MpItemVersionView): void { + const installed = item.type === ItemType.SOLUTION_TEMPLATE ? this.installedTemplates.find(i => i.itemId === item.itemId) : undefined; + const count = item.type === ItemType.DEVICE ? this.installedDeviceCounts[item.itemId] || 0 : 0; + this.actions.openItemDetail(item, installed, count).subscribe(result => { + if (result === 'installed' || result === 'deleted') { + this.loadInstalled(); + } + }); + } + + browse(route: string): void { + this.router.navigate(['/iot-hub', route]); + } + + openSearch(): void { + this.searching.set(true); + setTimeout(() => this.searchInput?.nativeElement.focus()); + } + + closeSearch(focusOpener = true): void { + this.query.set(''); + this.searching.set(false); + if (focusOpener) { + setTimeout(() => this.searchOpener?.nativeElement.focus()); + } + } + + clearSearch(): void { + this.query.set(''); + this.searchInput?.nativeElement.focus(); + } + + search(): void { + const search = this.query().trim(); + if (search) { + this.router.navigate(['/iot-hub/search'], {queryParams: {search}}); + } else { + this.searchInput?.nativeElement.focus(); + } + } + + onSearchKeydown(event: KeyboardEvent): void { + if (event.key === 'Enter') { + event.preventDefault(); + this.search(); + } else if (event.key === 'Escape') { + event.preventDefault(); + this.closeSearch(); + } + } + + onSearchFocusOut(event: FocusEvent): void { + const field = (event.currentTarget as HTMLElement); + if (!field.contains(event.relatedTarget as Node) && !this.query().trim()) { + this.closeSearch(false); + } + } + + private load(): void { + const cached = readSnapshot(); + if (cached) { + this.apply(cached); + } + const config = {ignoreLoading: true, ignoreErrors: true}; + const sortOrder: SortOrder = {property: 'totalInstallCount', direction: Direction.DESC}; + const query = (type: ItemType) => new MpItemVersionQuery(new PageLink(SHOWN, 0, null, sortOrder), {type}); + forkJoin({ + templates: this.api.getPublishedVersions(query(ItemType.SOLUTION_TEMPLATE), config), + devices: this.api.getPublishedVersions(query(ItemType.DEVICE), config) + }).subscribe({ + next: ({templates, devices}) => { + const snapshot = {at: Date.now(), templates: templates.data, devices: devices.data, deviceTotal: devices.totalElements}; + writeSnapshot(snapshot); + this.apply(snapshot); + }, + error: () => { + if (!cached) { + this.failed.set(true); + this.loaded.set(true); + } + } + }); + this.loadInstalled(); + } + + private apply(snapshot: HubSnapshot): void { + this.templates.set(snapshot.templates.map((item, i) => + this.tile(item, TEMPLATE_TINTS[i % TEMPLATE_TINTS.length], item.useCases?.[0] ?? ''))); + this.devices.set(snapshot.devices.map((item, i) => this.tile(item, DEVICE_TINTS[i % DEVICE_TINTS.length], this.deviceMeta(item)))); + this.deviceTotal.set(snapshot.deviceTotal); + this.loaded.set(true); + } + + private loadInstalled(): void { + const config = {ignoreLoading: true, ignoreErrors: true}; + forkJoin({ + templates: this.api.getInstalledItems(new PageLink(10000, 0), ItemType.SOLUTION_TEMPLATE, undefined, config), + deviceCounts: this.api.getInstalledItemCounts(ItemType.DEVICE, config) + }).subscribe({ + next: ({templates, deviceCounts}) => { + this.installedTemplates = templates.data; + this.installedDeviceCounts = deviceCounts; + this.templates.update(tiles => [...tiles]); + }, + error: () => {} + }); + } + + private tile(item: MpItemVersionView, tint: string, meta: string): HubTile { + return {item, tint: `linear-gradient(135deg, ${tint})`, image: this.preview(item), meta}; + } + + private deviceMeta(item: MpItemVersionView): string { + const vendor = item.dataDescriptor?.vendor; + const connectivity: string[] = item.dataDescriptor?.connectivity ?? []; + const via = item.dataDescriptor?.hardwareType === 'Gateway' ? 'Gateway' : connectivity[connectivity.length - 1]; + return [vendor, via].filter(Boolean).join(' · '); + } + + private preview(item: MpItemVersionView): string | null { + if (!item.image) { + return null; + } + const [path, params] = item.image.split('?'); + const withPreview = path.endsWith('/preview') ? path : `${path}/preview`; + return this.api.resolveResourceUrl(params ? `${withPreview}?${params}` : withPreview); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html new file mode 100644 index 0000000000..97a8d74549 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html @@ -0,0 +1,166 @@ + + + + @if (managed() && updatedAgo()) { + + {{ 'subscription.updated-ago' | translate: {ago: updatedAgo()} }} + + + } + + @if (info(); as license) { +
+ + + @if (license.offline) { + + cloud_off + + } + +
+ {{ (license.development ? 'home.license.development-mode' : license.perpetual ? 'subscription.perpetual-license' : 'subscription.subscription') | translate }} + {{ license.subscriptionPlanName }} + @if (license.development) { + {{ 'home.license.development-line' | translate }} + } @else if (license.perpetual) { + @if (license.endTs) { + {{ 'subscription.updates-and-support-until' | translate: {date: license.endTs | date: 'd MMMM yyyy'} }} + } + } @else if (license.upcomingInvoiceDate) { + + } +
+ @if (managed()) { +
+ +
+ } +
+
+ @if (limitGroups().length) { +
+ @for (group of limitGroups(); track group.id) { +
{{ group.icon }}{{ group.label | translate }}
+ @for (row of group.rows; track row.itemType) { +
+ {{ row.label | translate }} + @if (row.max) { + + {{ row.used | shortNumber: {roundDown: true} }} / {{ row.max | shortNumber: {roundDown: true} }} + @if (row.tone) { + {{ (row.tone === 'critical' ? 'home.license.at-limit' : 'home.license.of-limit') | translate: {percent: row.percent} }} + } + + } @else { + {{ 'subscription.not-included' | translate }} + } + + @if (row.action === 'add') { + + } @else if (row.action === 'upgrade') { + + } @else if (row.max) { + {{ row.percent }}% + } @else { + + } +
+ } + } +
+ } + @switch (offer()) { + @case ('pe-pack') { +
+
+ +
+ {{ 'subscription.pe-pack' | translate }} + {{ 'subscription.pe-pack-desc' | translate }} +
+ +
+ +
+ } + @case ('production') { +
+
+
+ {{ 'home.license.go-to-production' | translate }} +
+ +
+ +
+ } + @default { +
+
extension{{ 'subscription.add-ons' | translate }}
+
    + @for (addon of addons(); track addon.type) { +
  • + {{ addon.label | translate }} + @switch (addon.state) { + @case ('included') { + check_circle{{ 'subscription.included' | translate }} + } + @case ('add') { + + } + @case ('upgrade') { + + } + @case ('not-included') { + {{ 'subscription.not-included' | translate }} + } + @default { + {{ 'home.license.not-in-license' | translate }} + } + } +
  • + } +
+
+ } + } +
+ } +
+ + +
    + @for (item of items; track item.icon) { +
  • + {{ item.icon }} + {{ item.title | translate }}{{ item.text | translate }} +
  • + } +
+
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss new file mode 100644 index 0000000000..af4b9821e7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss @@ -0,0 +1,537 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; + container: tb-license / inline-size; +} + +.tb-license-updated { + display: inline-flex; + align-items: center; + gap: 2px; + margin-right: -8px; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + > span { + white-space: nowrap; + } +} + +.tb-license-refresh.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + + &.spinning { + animation: tb-license-spin 1s linear infinite; + } + } +} + +@keyframes tb-license-spin { + to { + transform: rotate(360deg); + } +} + +.tb-license-band { + --tb-license-holo: color-mix(in srgb, var(--tb-primary-500) 14%, transparent); + position: relative; + isolation: isolate; + display: flex; + align-items: center; + gap: 20px; + margin: 0 calc(-1 * var(--tb-home-card-padding, 20px)) 8px; + padding: 24px var(--tb-home-card-padding, 20px); + + &::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + pointer-events: none; + background: + radial-gradient(50% 70% at 50% 0%, rgb(255 255 255 / 0.7), rgb(255 255 255 / 0) 70%), + linear-gradient(105deg, var(--tb-license-holo) 0%, rgb(0 150 220 / 0.10) 22%, rgb(150 120 240 / 0.09) 42%, + rgb(255 170 130 / 0.08) 60%, rgb(0 190 170 / 0.09) 78%, var(--tb-license-holo) 100%); + background-size: 100% 100%, 220% 100%; + -webkit-mask-image: linear-gradient(180deg, #000 0%, #000 55%, transparent 100%); + mask-image: linear-gradient(180deg, #000 0%, #000 55%, transparent 100%); + animation: tb-license-holo 18s ease-in-out both; + } + + &.grant { + --tb-license-holo: rgb(21 96 180 / 0.14); + } + + &.development::before { + animation: none; + background: radial-gradient(circle at 1px 1px, rgb(15 36 32 / 0.09) 1px, transparent 1.5px) 0 0 / 12px 12px, rgba(0, 0, 0, 0.03); + } +} + +@keyframes tb-license-holo { + from { + background-position: 0 0, 0% 0; + } + to { + background-position: 0 0, 100% 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-license-band::before { + animation: none; + } +} + +.tb-license-mark { + position: relative; + display: block; + flex: none; + width: 72px; + height: 72px; + margin: -6px; + + img { + display: block; + width: 100%; + height: 100%; + } + + &.development img { + filter: grayscale(1); + opacity: 0.72; + } + + &.with-hue::after { + content: ""; + position: absolute; + inset: 0; + background: var(--tb-noncommercial, #1560b4); + mix-blend-mode: hue; + pointer-events: none; + -webkit-mask: url(/assets/license/tb-license-mark.svg) center / 100% 100% no-repeat; + mask: url(/assets/license/tb-license-mark.svg) center / 100% 100% no-repeat; + } +} + +.tb-license-offline { + position: absolute; + top: -2px; + right: -2px; + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: #fff; + box-shadow: 0 1px 3px rgba(15, 36, 32, 0.22); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + } +} + +.tb-license-id { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; + + small { + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.5px; + text-transform: uppercase; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + } + + > b { + font: 500 20px/28px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + > span { + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + ::ng-deep b { + font-weight: 500; + } + } +} + +.tb-license-manage { + display: flex; + flex: none; + flex-direction: column; + align-items: flex-end; + gap: 4px; +} + +.tb-license-button.mdc-button { + height: 32px; + padding: 0 16px; + border-radius: 4px; + white-space: nowrap; + + &.mat-mdc-outlined-button { + background: var(--tb-surface, #fff); + } + + .mat-icon { + width: 18px; + height: 18px; + margin: 0 8px 0 -4px; + font-size: 18px; + } +} + +.tb-license-body { + display: flex; + flex-direction: column; + gap: 16px; +} + +.tb-license-head { + display: flex; + align-items: center; + gap: 6px; + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.5px; + text-transform: uppercase; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + flex: none; + width: 16px; + height: 16px; + font-size: 16px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } +} + +.tb-license-limits { + display: grid; + grid-template-columns: max-content max-content minmax(48px, 1fr) max-content; + align-items: center; + gap: 8px 12px; + min-width: 0; + max-width: 560px; + + > .tb-license-head { + grid-column: 1 / -1; + margin-top: 16px; + + &:first-child { + margin-top: 0; + } + } +} + +.tb-license-limit { + display: contents; + + > * { + display: flex; + align-items: center; + min-height: 32px; + } + + > .tb-license-meter { + display: block; + min-height: 0; + } + + > .tb-license-button { + justify-self: start; + min-height: 0; + margin-left: -8px; + } +} + +.tb-license-limit-name { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-license-limit-counts { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-license-limit-counts.none { + font-size: 13px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-license-meter { + height: 8px; + overflow: hidden; + border-radius: 2px; + background: rgba(0, 0, 0, 0.08); + + > i { + display: block; + height: 100%; + border-radius: 2px; + background: var(--tb-primary-500); + } +} + +.tb-license-pct { + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + font-variant-numeric: tabular-nums; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-license-limit.near { + .tb-license-limit-counts { + color: #955400; + } + + .tb-license-meter { + background: rgb(255 167 38 / 0.16); + + > i { + background: #b26500; + } + } +} + +.tb-license-limit.critical { + .tb-license-limit-counts { + color: var(--tb-sev-critical, #D12730); + } + + .tb-license-meter { + background: rgba(209, 39, 48, 0.06); + + > i { + background: var(--tb-sev-critical, #D12730); + } + } +} + +.tb-license-addons-group { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.tb-license-addons { + display: grid; + grid-template-columns: max-content max-content; + align-items: center; + gap: 8px 16px; + margin: 0; + padding: 0; + list-style: none; + + li { + display: contents; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + > * { + display: flex; + align-items: center; + min-height: 32px; + } + + > .tb-license-button { + justify-self: start; + min-height: 0; + } + } +} + +.tb-license-addon-name { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.tb-license-addon-state { + display: inline-flex; + align-items: center; + gap: 4px; + padding-left: 8px; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + &.included { + 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); + } +} + +.tb-license-pack { + min-width: 0; + padding: 12px 14px 14px; + border-radius: 10px; + background: + linear-gradient(180deg, rgb(255 255 255 / 0) 35%, var(--tb-surface, #fff) 100%), + radial-gradient(120% 110% at 0% 0%, rgb(255 255 255 / 0.9) 0%, rgb(255 255 255 / 0) 58%), + linear-gradient(115deg, rgb(0 105 92 / 0.11) 0%, rgb(0 105 92 / 0.06) 38%, rgb(0 88 196 / 0.065) 72%, rgb(0 51 202 / 0.10) 100%); +} + +.tb-license-pack-head { + display: flex; + align-items: center; + gap: 10px; + margin: -4px 0 10px -4px; + + img { + flex: none; + } + + &.bare { + margin: 0 0 12px; + } +} + +.tb-license-pack-id { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; + + b { + font: 500 15px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + span { + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.tb-license-pack-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; + margin: 0; + padding: 0; + list-style: none; + + li { + display: flex; + gap: 9px; + padding: 10px 12px 11px; + border-radius: 8px; + background: var(--tb-surface, #fff); + box-shadow: 0 0 0 1px rgb(0 105 92 / 0.06), 0 1px 2px rgba(15, 36, 32, 0.04); + + > .mat-icon { + flex: none; + width: 20px; + height: 20px; + margin-top: 1px; + font-size: 20px; + color: #023e36; + } + + > span { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + } + } + + b { + font: 500 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + small { + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } +} + +@container tb-license (min-width: 640px) { + .tb-license-body:not(.offer) { + display: grid; + grid-template-columns: minmax(0, 1fr) max-content; + align-items: start; + column-gap: 40px; + } + + .tb-license-body:not(.offer) .tb-license-limits { + max-width: none; + } +} + +@container tb-license (max-width: 460px) { + .tb-license-limits { + grid-template-columns: max-content max-content minmax(48px, 1fr); + } + + .tb-license-limit { + > .tb-license-button { + grid-column: 1 / -1; + } + + > .tb-license-pct { + display: none; + } + } +} + +@container tb-license (max-width: 420px) { + .tb-license-band { + flex-wrap: wrap; + } + + .tb-license-manage { + flex-basis: 100%; + flex-direction: row; + justify-content: space-between; + align-items: center; + } + + .tb-license-pack-grid { + grid-template-columns: minmax(0, 1fr); + } + + .tb-license-pack-head { + flex-wrap: wrap; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts new file mode 100644 index 0000000000..a5aa2f231d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts @@ -0,0 +1,321 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { interval } from 'rxjs'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { AdminService } from '@core/http/admin.service'; +import { DateAgoPipe } from '@shared/pipe/date-ago.pipe'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { + AddonType, + addonTypeTranslationMap, + PlanUiType, + SubscriptionInfo, + usageAddItemTypeTranslationMap, + UsageItemType, + usageItemTypeTranslationMap +} from '@shared/models/subscription.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { + LicenseActionsService, + licenseLimitCritical, + licenseLimitWarn, + licenseMeterWidth +} from '@home/components/license/license-actions.service'; + +const LOADING_HEIGHT = 398; +const HEIGHT_KEY = 'tb-home-license-height'; + +const storedHeight = (): number => { + return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT; +}; + +const AGO_REFRESH_MS = 30_000; + +const PLANS_URL = 'https://thingsboard.io/pricing/?product=thingsboard-pe'; + +const TONED_ITEMS = [UsageItemType.DEVICES, UsageItemType.ASSETS, UsageItemType.AI_CREDITS]; + +type LimitTone = 'critical' | 'near' | null; + +type LimitAction = 'add' | 'upgrade' | null; + +interface LicenseLimit { + itemType: UsageItemType; + label: string; + used: number; + max: number; + percent: number; + width: number; + tone: LimitTone; + action: LimitAction; + addLabel: string; +} + +interface LicenseLimitGroup { + id: string; + label: string; + icon: string; + rows: LicenseLimit[]; +} + +type AddonState = 'included' | 'not-included' | 'add' | 'upgrade' | 'not-in-license'; + +interface LicenseAddon { + type: AddonType; + label: string; + state: AddonState; +} + +interface LicenseOffer { + icon: string; + title: string; + text: string; +} + +const PE_PACK_OFFERS: LicenseOffer[] = [ + {icon: 'brush', title: 'subscription.white-labeling', text: 'subscription.white-labeling-promo'}, + {icon: 'integration_instructions', title: 'subscription.integrations', text: 'subscription.integrations-promo'}, + {icon: 'schedule', title: 'subscription.scheduler', text: 'subscription.scheduler-promo'}, + {icon: 'assessment', title: 'subscription.reports', text: 'subscription.reports-promo'} +]; + +const PRODUCTION_OFFERS: LicenseOffer[] = [ + {icon: 'rocket_launch', title: 'home.license.production-use', text: 'home.license.production-use-text'}, + {icon: 'brush', title: 'subscription.white-labeling', text: 'subscription.white-labeling-promo'}, + {icon: 'auto_awesome', title: 'subscription.ai-credits', text: 'home.license.ai-credits-text'}, + {icon: 'extension', title: 'subscription.add-ons', text: 'home.license.add-ons-text'} +]; + +@Component({ + selector: 'tb-license-home', + templateUrl: './license-home.component.html', + styleUrls: ['./license-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class LicenseHomeComponent { + + private adminService = inject(AdminService); + private dateAgoPipe = inject(DateAgoPipe); + private licenseActions = inject(LicenseActionsService); + private aiEnabled = getCurrentAuthState(inject(Store)).aiEnabled; + + readonly pePackOffers = PE_PACK_OFFERS; + readonly productionOffers = PRODUCTION_OFFERS; + + readonly info = signal(null); + readonly refreshing = signal(false); + private readonly now = signal(Date.now()); + + readonly cardDefinition = computed(() => { + const card = HOME_CARDS[HomeCardId.LICENSE]; + return this.info() ? card : {...card, height: storedHeight()}; + }); + + readonly kind = computed(() => { + const info = this.info(); + if (!info) { + return null; + } + if (info.development) { + return 'development'; + } + if (info.communityGrantLicense) { + return 'grant'; + } + return info.perpetual ? 'perpetual' : 'subscription'; + }); + + readonly markHue = computed(() => { + switch (this.info()?.planUiType) { + case PlanUiType.TbNonCommercial: + case PlanUiType.TbNonCommercialOffline: + case PlanUiType.TbCommunityGrant: + return true; + default: + return false; + } + }); + + readonly managed = computed(() => { + const info = this.info(); + return !!info && !info.offline && !info.nonProduction; + }); + + readonly updatedAgo = computed(() => { + this.now(); + const dataTs = this.info()?.dataTs; + return dataTs ? this.dateAgoPipe.transform(dataTs, {applyAgo: true, long: true, textPart: true}) : null; + }); + + readonly limitGroups = computed(() => { + const info = this.info(); + if (!info || info.development) { + return []; + } + const groups: LicenseLimitGroup[] = []; + const entities = [ + this.limit(info, UsageItemType.DEVICES, info.devicesCount, info.maxDevices, info.planExtraDeviceEnabled), + this.limit(info, UsageItemType.ASSETS, info.assetsCount, info.maxAssets, false) + ].filter(row => !!row); + if (entities.length) { + groups.push({id: 'entities', label: 'home.license.devices-and-assets', icon: 'memory', rows: entities}); + } + const installations = [ + info.maxInstances > 0 ? + this.limit(info, UsageItemType.PROD_INSTANCES, info.instancesCount, info.maxInstances, info.planExtraInstanceEnabled) : null, + info.edgeEnabled ? this.limit(info, UsageItemType.EDGES, info.edgesCount, info.maxEdges, info.planExtraEdgeEnabled) : null, + info.maxAgents > 0 || info.planExtraAgentEnabled ? + this.limit(info, UsageItemType.AGENTS, info.agentsCount, info.maxAgents, info.planExtraAgentEnabled) : null + ].filter(row => !!row); + if (installations.length) { + groups.push({id: 'installations', label: 'home.license.installations', icon: 'lan', rows: installations}); + } + if (this.aiEnabled && !info.offline && info.maxAiCredits > 0) { + const credits = this.limit(info, UsageItemType.AI_CREDITS, info.usedAiCredits, info.maxAiCredits, info.planExtraAiCreditsEnabled, + 'home.license.this-month'); + groups.push({id: 'credits', label: 'subscription.ai-credits', icon: 'auto_awesome', rows: [credits]}); + } + return groups; + }); + + readonly offer = computed<'pe-pack' | 'production' | null>(() => { + const info = this.info(); + if (!info) { + return null; + } + if (info.development) { + return 'production'; + } + return info.communityGrantLicense && !info.whiteLabelingEnabled ? 'pe-pack' : null; + }); + + readonly addons = computed(() => { + const info = this.info(); + if (!info || this.offer()) { + return []; + } + const addons: LicenseAddon[] = []; + if (!info.communityGrantLicense || info.whiteLabelingEnabled) { + addons.push(this.addon(info, AddonType.WHITE_LABELING, info.whiteLabelingEnabled, false)); + } + if (!info.perpetual || info.planEdgeEnabled) { + addons.push(this.addon(info, AddonType.EDGE, info.edgeEnabled, info.planEdgeEnabled)); + } + if (!info.perpetual || info.planTrendzEnabled) { + addons.push(this.addon(info, AddonType.TRENDZ, info.trendzEnabled, info.planTrendzEnabled)); + } + if (info.communityGrantLicense && info.whiteLabelingEnabled) { + addons.push(this.addon(info, AddonType.PROFESSIONAL_UPGRADE, true, false)); + } + return addons; + }); + + constructor() { + const destroyRef = inject(DestroyRef); + this.adminService.getSubscriptionInfo({ignoreLoading: true}).pipe(takeUntilDestroyed(destroyRef)) + .subscribe(info => this.info.set(info)); + interval(AGO_REFRESH_MS).pipe(takeUntilDestroyed(destroyRef)).subscribe(() => this.now.set(Date.now())); + const host = inject>(ElementRef); + const observer = new ResizeObserver(() => this.rememberHeight(host.nativeElement)); + observer.observe(host.nativeElement); + destroyRef.onDestroy(() => observer.disconnect()); + } + + refresh(): void { + this.refreshing.set(true); + this.adminService.refreshLicense({ignoreLoading: true}).subscribe({ + next: info => { + this.info.set(info); + this.refreshing.set(false); + }, + error: () => this.refreshing.set(false) + }); + } + + manageLicense(): void { + this.licenseActions.manageLicense(this.info()); + } + + limitAction(row: LicenseLimit): void { + if (row.action === 'add') { + this.licenseActions.addItems(this.info(), row.itemType); + } else if (row.action === 'upgrade') { + this.licenseActions.upgradePlanForItems(this.info(), row.itemType); + } + } + + addonAction(addon: LicenseAddon): void { + if (addon.state === 'add') { + this.licenseActions.addAddOn(this.info(), addon.type); + } else if (addon.state === 'upgrade') { + this.licenseActions.upgradePlanForAddon(this.info(), addon.type); + } + } + + addProfessionalPack(): void { + this.licenseActions.addAddOn(this.info(), AddonType.PROFESSIONAL_UPGRADE); + } + + seePlans(): void { + window.open(PLANS_URL, '_blank'); + } + + private rememberHeight(element: HTMLElement): void { + const height = Math.round(element.getBoundingClientRect().height); + if (!this.info() || !height) { + return; + } + writeStored(HEIGHT_KEY, String(height)); + } + + private limit(info: SubscriptionInfo, itemType: UsageItemType, used: number, max: number, addEnabled: boolean, + label = usageItemTypeTranslationMap.get(itemType)): LicenseLimit | null { + if (max == null || max < 0) { + return null; + } + const count = used ?? 0; + let tone: LimitTone = null; + if (max > 0 && count > max) { + tone = 'critical'; + } else if (TONED_ITEMS.includes(itemType)) { + tone = licenseLimitCritical(count, max) ? 'critical' : licenseLimitWarn(count, max) ? 'near' : null; + } + let action: LimitAction = null; + if ((tone || max === 0) && !info.offline && itemType !== UsageItemType.ASSETS) { + action = addEnabled ? 'add' : !info.perpetual ? 'upgrade' : null; + } + return { + itemType, + label, + used: count, + max, + percent: max > 0 ? Math.round(count / max * 100) : 0, + width: licenseMeterWidth(count, max), + tone, + action, + addLabel: usageAddItemTypeTranslationMap.get(itemType) + }; + } + + private addon(info: SubscriptionInfo, type: AddonType, enabled: boolean, addEnabled: boolean): LicenseAddon { + let state: AddonState; + if (enabled) { + state = 'included'; + } else if (info.offline) { + state = 'not-included'; + } else if (addEnabled) { + state = 'add'; + } else if (!info.perpetual) { + state = 'upgrade'; + } else { + state = 'not-in-license'; + } + return {type, label: addonTypeTranslationMap.get(type), state}; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.html new file mode 100644 index 0000000000..17433da81d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.html @@ -0,0 +1,41 @@ + + + @if (settings()) { +
+
+ + @if (badges()) { + + } +
+ @if (label()) { +
{{ label() }}
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.scss new file mode 100644 index 0000000000..d3f32b8d7d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.scss @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; + container: tb-mobile-app-home / inline-size; +} + +.tb-app-widget { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; +} + +.tb-app-widget-row { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; +} + +.badges-left .tb-app-widget-row { + flex-direction: row-reverse; +} + +.tb-app-qr { + flex: none; + box-sizing: border-box; + width: 96px; + height: 96px; + padding: 4px; + border-radius: 6px; + background: #fff; + + ::ng-deep svg { + display: block; + width: 100%; + height: 100%; + } +} + +.tb-store-badges { + display: flex; + flex-direction: column; + gap: 8px; +} + +.tb-store-badge { + display: inline-flex; + flex: none; + align-items: center; + gap: 8px; + box-sizing: border-box; + width: 136px; + height: 40px; + padding: 0 12px 0 10px; + border: 1px solid #a6a6a6; + border-radius: 7px; + background: #000; + color: #fff; + text-decoration: none; + white-space: nowrap; + transition: background-color .2s ease, border-color .2s ease; + + &:hover { + border-color: #c8c8c8; + background: #1f1f1f; + color: #fff; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } +} + +.tb-store-mark { + display: flex; + flex: none; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + + svg { + display: block; + width: 22px; + height: 22px; + } +} + +.apple .tb-store-mark svg { + width: 24px; + height: 24px; + margin-top: -2px; +} + +.tb-store-text { + display: flex; + flex-direction: column; + gap: 1px; + font-family: var(--tb-font, Roboto, sans-serif); + text-align: left; + + small { + font-size: 10px; + line-height: 11px; + letter-spacing: 0.1px; + opacity: 0.92; + } + + b { + font-size: 16px; + font-weight: 500; + line-height: 18px; + letter-spacing: -0.1px; + } +} + +.play .tb-store-text small { + font-size: 9px; + letter-spacing: 0.5px; + text-transform: uppercase; +} + +.tb-app-widget-label { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + text-align: center; + color: var(--tb-ink-60, rgba(0, 0, 0, 0.6)); +} + +@container tb-mobile-app-home (max-width: 290px) { + .tb-store-badges { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.ts new file mode 100644 index 0000000000..4def500228 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/mobile-app-home.component.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, signal } from '@angular/core'; +import { MobileApplicationService } from '@core/http/mobile-application.service'; +import { UtilsService } from '@core/services/utils.service'; +import { unwrapModule } from '@core/utils'; +import { BadgePosition, QrCodeSettings } from '@shared/models/mobile-app.models'; +import { MINUTE } from '@shared/models/time/time.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; + +@Component({ + selector: 'tb-mobile-app-home', + templateUrl: './mobile-app-home.component.html', + styleUrls: ['./mobile-app-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class MobileAppHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.MOBILE_APP]; + + private mobileAppService = inject(MobileApplicationService); + private utils = inject(UtilsService); + + readonly settings = signal(null); + + readonly qrCode = signal(''); + + readonly badges = computed(() => { + const settings = this.settings(); + return !!settings?.qrCodeConfig?.badgeEnabled && (settings.iosEnabled || settings.androidEnabled); + }); + + readonly badgesLeft = computed(() => this.settings()?.qrCodeConfig?.badgePosition === BadgePosition.LEFT); + + readonly label = computed(() => { + const config = this.settings()?.qrCodeConfig; + return config?.qrCodeLabelEnabled ? config.qrCodeLabel : ''; + }); + + private deepLink = ''; + private deepLinkTimer: ReturnType | null = null; + private destroyed = false; + + constructor() { + this.mobileAppService.getMergedMobileAppSettings().subscribe(settings => this.settings.set(settings)); + this.loadDeepLink(); + inject(DestroyRef).onDestroy(() => { + this.destroyed = true; + clearTimeout(this.deepLinkTimer); + }); + } + + openDeepLink(): void { + if (this.deepLink && window.matchMedia('(pointer: coarse)').matches) { + window.open(this.deepLink, '_blank'); + } + } + + private loadDeepLink(): void { + clearTimeout(this.deepLinkTimer); + this.mobileAppService.getMobileAppDeepLink().subscribe(link => { + if (this.destroyed) { + return; + } + this.deepLink = link; + import('qrcode').then(QRCode => unwrapModule(QRCode).toString(link, {type: 'svg', margin: 0}, (_error: Error, svg: string) => { + if (!this.destroyed) { + this.qrCode.set(svg); + } + })); + const ttl = Number(this.utils.getQueryParam('ttl', link)) * MINUTE; + if (ttl > 0) { + this.deepLinkTimer = setTimeout(() => this.loadDeepLink(), ttl); + } + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.html new file mode 100644 index 0000000000..9a8ec4c53c --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.html @@ -0,0 +1,65 @@ + + + + @if (rows().length) { + + } + + @if (loaded()) { + @if (!rows().length) { +
+ + {{ 'home.notifications.none' | translate }} +
+ } @else { +
+ @for (row of rows(); track row.id) { +
+ @if (row.severity) { + + } @else { + {{ row.icon }} + } +
+
+
+ @if (openId() === row.id) { +
+ {{ row.ago }} · {{ row.when }} + @if (row.action) { + + } +
+ } +
+
+ {{ row.ago }} + +
+
+ } +
+ + } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.scss new file mode 100644 index 0000000000..ebb96c5c98 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.scss @@ -0,0 +1,237 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; + +:host { + display: block; + min-width: 0; +} + +.tb-notifications-mark-all .mat-icon { + display: none; +} + +.tb-mark-all-icon .tb-notifications-mark-all { + width: 40px; + min-width: 40px; + height: 40px; + padding: 0; + border-radius: 50%; + justify-content: center; + + .mat-icon { + display: inline-block; + width: 20px; + height: 20px; + margin: 0; + font-size: 20px; + } + + .tb-notifications-mark-all-label { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + } +} + +.tb-notifications-list { + display: flex; + flex-direction: column; + margin-top: -4px; +} + +.tb-notification { + display: grid; + grid-template-columns: 20px minmax(0, 1fr) auto; + column-gap: 16px; + align-items: start; + padding: 8px 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + cursor: pointer; + + &:last-child { + border-bottom: none; + padding-bottom: 2px; + } + + &:hover .tb-notification-title { + text-decoration-line: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 4px; + } + + &:hover, &:focus-within { + .tb-notification-mark-read { + opacity: 1; + pointer-events: auto; + } + + .tb-notification-time { + visibility: hidden; + } + } + + &.open { + cursor: default; + margin: 0 -8px; + padding-left: 8px; + padding-right: 8px; + border-radius: 6px; + background: rgba(0, 0, 0, 0.025); + + &:hover .tb-notification-title { + text-decoration: none; + } + + .tb-notification-title, .tb-notification-message { + white-space: normal; + overflow: visible; + overflow-wrap: anywhere; + } + + .tb-notification-time { + visibility: hidden; + } + + .tb-notification-mark-read { + opacity: 1; + pointer-events: auto; + } + } +} + +.tb-notification-icon { + width: 20px; + height: 20px; + font-size: 20px; + line-height: 20px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-notification-mark { + display: inline-flex; + align-items: center; + justify-content: center; + + ::ng-deep svg { + width: 18px; + height: 18px; + } +} + +.tb-notification-content { + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; + letter-spacing: 0.2px; +} + +.tb-notification-title { + overflow: hidden; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-notification-message { + overflow: hidden; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-notification-meta { + position: relative; + display: flex; + justify-content: flex-end; + min-width: 28px; + height: 20px; + padding-left: 4px; +} + +.tb-notification-time { + font: 400 12px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} + +.mat-mdc-icon-button.tb-notification-mark-read { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + position: absolute; + top: -6px; + right: -6px; + width: 32px; + height: 32px; + padding: 6px; + opacity: 0; + pointer-events: none; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } + + &:hover { + color: var(--tb-primary-500); + } +} + +@media (hover: none) { + .tb-notification-meta { + flex-direction: column; + align-items: flex-end; + gap: 2px; + height: auto; + } + + .mat-mdc-icon-button.tb-notification-mark-read { + position: relative; + top: 0; + right: 0; + margin-right: -6px; + opacity: 1; + pointer-events: auto; + } + + .tb-notification:hover .tb-notification-time, .tb-notification:focus-within .tb-notification-time { + visibility: visible; + } +} + +.tb-notification-detail { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 4px 12px; + margin-top: 4px; + + .mat-mdc-button { + margin-right: -8px; + } +} + +.tb-notification-when { + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts new file mode 100644 index 0000000000..c3edd35416 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterNextRender, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + NgZone, + SecurityContext, + signal +} from '@angular/core'; +import { Router } from '@angular/router'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { filter } from 'rxjs/operators'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { homeAgo, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; +import { NotificationWebsocketService } from '@core/ws/notification-websocket.service'; +import { NotificationSubscriber } from '@shared/models/telemetry/telemetry.models'; +import { ActionButtonLinkType, Notification, NotificationType, NotificationTypeIcons } from '@shared/models/notification.models'; +import { UtilsService } from '@core/services/utils.service'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { StateObject } from '@core/api/widget-api.models'; +import { MINUTE } from '@shared/models/time/time.models'; +import { objToBase64URI } from '@core/utils'; + +const LIMIT = 10; + +interface NotificationHomeRow { + id: string; + notification: Notification; + icon: string; + iconColor: string | null; + severity: string | null; + title: string; + message: string; + ago: string; + when: string; + action: string | null; +} + +@Component({ + selector: 'tb-notifications-home', + templateUrl: './notifications-home.component.html', + styleUrls: ['./notifications-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class NotificationsHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.NOTIFICATIONS]; + readonly inboxLink = '/notification/inbox'; + + private notificationWsService = inject(NotificationWebsocketService); + private zone = inject(NgZone); + private router = inject(Router); + private sanitizer = inject(DomSanitizer); + private translate = inject(TranslateService); + private utils = inject(UtilsService); + private toast = inject(ToastNotificationService); + private host = inject(ElementRef); + + private readonly notifications = signal(null); + private readonly now = signal(Date.now()); + + readonly total = signal(0); + readonly expanded = signal(false); + readonly openId = signal(null); + readonly markAllIcon = signal(false); + + readonly loaded = computed(() => this.notifications() !== null); + + readonly listed = computed(() => Math.max(this.total(), this.notifications()?.length ?? 0)); + + readonly rows = computed(() => { + const now = this.now(); + const list = this.notifications() ?? []; + return list.slice(0, homeListShown(this.listed(), this.expanded())).map(notification => this.toRow(notification, now)); + }); + + private subscriber = NotificationSubscriber.createNotificationsSubscription(this.notificationWsService, this.zone, LIMIT); + + constructor() { + const destroyRef = inject(DestroyRef); + this.subscriber.notifications$.pipe( + filter((value): value is Notification[] => Array.isArray(value)) + ).subscribe(list => this.notifications.set([...list])); + this.subscriber.notificationCount$.subscribe(count => this.total.set(count)); + this.subscriber.subscribe(); + const tick = setInterval(() => this.now.set(Date.now()), MINUTE); + let observer: ResizeObserver | null = null; + afterNextRender(() => { + observer = new ResizeObserver(() => this.measureHeader()); + observer.observe(this.host.nativeElement); + }); + destroyRef.onDestroy(() => { + clearInterval(tick); + observer?.disconnect(); + this.subscriber.unsubscribe(); + }); + } + + toggle(row: NotificationHomeRow, event?: Event): void { + if (event && (event.target as HTMLElement).closest('button, a')) { + return; + } + this.openId.set(this.openId() === row.id ? null : row.id); + } + + onRowKeydown(row: NotificationHomeRow, event: KeyboardEvent): void { + if (event.target !== event.currentTarget) { + return; + } + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + this.toggle(row); + } else if (event.key === 'Escape' && this.openId() === row.id) { + this.openId.set(null); + } + } + + markAsRead(row: NotificationHomeRow, event: Event): void { + event.stopPropagation(); + NotificationSubscriber.createMarkAsReadCommand(this.notificationWsService, [row.id]).subscribe(); + this.notify(this.translate.instant('home.notifications.marked-read')); + } + + markAllAsRead(): void { + const count = this.total(); + NotificationSubscriber.createMarkAllAsReadCommand(this.notificationWsService).subscribe(); + this.openId.set(null); + this.notify(this.translate.instant(count === 1 ? 'home.notifications.marked-read' : 'home.notifications.marked-all-read', {count})); + } + + runAction(row: NotificationHomeRow, event: Event): void { + event.stopPropagation(); + const config = row.notification.additionalConfig.actionButtonConfig; + let link: string; + if (config.linkType === ActionButtonLinkType.DASHBOARD) { + let state: string = null; + if (config.dashboardState || config.setEntityIdInState) { + const stateObject: StateObject = { + params: config.setEntityIdInState ? {entityId: row.notification.info?.stateEntityId ?? null} : {} + }; + if (config.dashboardState) { + stateObject.id = config.dashboardState; + } + state = objToBase64URI([stateObject]); + } + link = `/dashboards/${config.dashboardId}` + (state ? `?state=${state}` : ''); + } else { + link = config.link; + } + if (link.startsWith('/')) { + this.router.navigateByUrl(this.router.parseUrl(link)); + } else { + window.open(link, '_blank'); + } + } + + private measureHeader(): void { + const element: HTMLElement = this.host.nativeElement; + const title = element.querySelector('.tb-home-card-title-group'); + const button = element.querySelector('.tb-notifications-mark-all'); + if (!title || !button) { + return; + } + this.zone.run(() => this.markAllIcon.set(false)); + requestAnimationFrame(() => { + const wrapped = button.getBoundingClientRect().top >= title.getBoundingClientRect().bottom - 4; + this.zone.run(() => this.markAllIcon.set(wrapped)); + }); + } + + private toRow(notification: Notification, now: number): NotificationHomeRow { + const createdTime = notification.createdTime ?? now; + const ownIcon = notification.additionalConfig?.icon?.enabled ? notification.additionalConfig.icon : null; + const alarm = notification.type === NotificationType.ALARM; + const button = notification.additionalConfig?.actionButtonConfig; + return { + id: notification.id.id, + notification, + icon: ownIcon?.icon ?? NotificationTypeIcons.get(notification.type) ?? 'notifications', + iconColor: ownIcon?.color ?? this.iconColor(notification.type), + severity: alarm ? notification.info?.alarmSeverity ?? null : null, + title: this.sanitizer.sanitize(SecurityContext.HTML, this.utils.customTranslation(notification.subject)), + message: this.sanitizer.sanitize(SecurityContext.HTML, this.utils.customTranslation(notification.text)), + ago: homeAgo(this.translate, now - createdTime), + when: this.exactTime(createdTime), + action: button?.enabled ? this.utils.customTranslation(button.text) : null + }; + } + + private exactTime(ts: number): string { + const date = new Date(ts); + const month = date.toLocaleString(this.translate.currentLang?.replace('_', '-') || 'en-US', {month: 'short'}); + const pad = (value: number) => String(value).padStart(2, '0'); + return `${pad(date.getDate())} ${month}, ${pad(date.getHours())}:${pad(date.getMinutes())}`; + } + + private iconColor(type: NotificationType): string | null { + switch (type) { + case NotificationType.RULE_ENGINE_COMPONENT_LIFECYCLE_EVENT: + return '#D12730'; + case NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST: + case NotificationType.ADDON_ACCESS_REQUEST: + case NotificationType.ADDON_ACCESS_ERROR: + case NotificationType.PLAN_UPGRADE_REQUEST: + case NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST: + return 'var(--tb-primary-500)'; + default: + return null; + } + } + + private notify(message: string): void { + this.toast.dispatchNotification(homeToast(message)); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.html new file mode 100644 index 0000000000..e20b7a1053 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.html @@ -0,0 +1,33 @@ + +@if (shown()) { +
+ +
+

{{ 'home.release.title' | translate: {version: update().latestVersion} }}

+

+ {{ 'home.release.read-notes' | translate }} + {{ 'home.release.notes' | translate }} +

+ +
+ +
+} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.scss new file mode 100644 index 0000000000..6894c6bde8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.scss @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: contents; +} + +.tb-release { + position: relative; + display: flex; + align-items: center; + gap: 16px; + box-sizing: border-box; + min-width: 0; + padding: 20px; + border-radius: 12px; + background: var(--tb-surface, #fff); + box-shadow: var(--tb-home-card-shadow); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-release-mark { + position: relative; + display: inline-block; + flex: none; + width: 56px; + height: 56px; + + > img { + display: block; + width: 100%; + height: 100%; + } +} + +.tb-release-badge { + position: absolute; + top: -2px; + right: -2px; + display: flex; + align-items: center; + justify-content: center; + width: 34%; + height: 34%; + border-radius: 50%; + background: var(--tb-primary-500); + box-shadow: 0 0 0 2px var(--tb-surface, #fff); + + .mat-icon { + width: auto; + height: auto; + font-size: 13px; + line-height: 1; + color: var(--tb-surface, #fff); + } +} + +.tb-release-body { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; +} + +.tb-release-title { + margin: 0; + font: 600 16px/24px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.15px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-release-line { + margin: 0; + font-size: 14px; + line-height: 20px; + letter-spacing: 0.2px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + a { + font-weight: 500; + white-space: nowrap; + text-decoration: none; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + border-bottom: 1px solid var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + + &:hover { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + border-bottom-color: currentColor; + } + } +} + +.tb-release-actions { + display: flex; + flex: none; + align-items: center; + gap: 4px; + margin-right: -8px; +} + +.tb-release-upgrade.mdc-button { + height: 32px; + padding: 0 16px; + border-radius: 4px; +} + +.tb-release-hide.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.tb-release-phone { + display: none; +} + +@media (max-width: 599px) { + .tb-release { + align-items: flex-start; + gap: 12px; + padding-right: 44px; + } + + .tb-release-mark { + width: 40px; + height: 40px; + + .tb-release-badge .mat-icon { + font-size: 10px; + } + } + + .tb-release-actions { + position: absolute; + top: 8px; + right: 8px; + margin: 0; + + > .tb-release-upgrade { + display: none; + } + } + + .tb-release-phone { + display: flex; + margin-top: 10px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts new file mode 100644 index 0000000000..9d84d330e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { UpdateMessage } from '@shared/models/settings.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; + +@Component({ + selector: 'tb-product-release-home', + templateUrl: './product-release-home.component.html', + styleUrls: ['./product-release-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class ProductReleaseHomeComponent { + + private translate = inject(TranslateService); + private toast = inject(ToastNotificationService); + private sysAdminHome = inject(SysAdminHomeService); + + readonly update = signal(null); + + readonly shown = computed(() => { + const update = this.update(); + return !!update?.updateAvailable && this.sysAdminHome.hiddenRelease() !== update.latestVersion; + }); + + constructor() { + this.sysAdminHome.update$.subscribe(update => this.update.set(update)); + } + + hide(): void { + const version = this.update().latestVersion; + this.sysAdminHome.setHiddenRelease(version); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.release.hidden', {version}), { + label: this.translate.instant('home.customize.undo'), + action: () => this.sysAdminHome.setHiddenRelease(null) + })); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.html new file mode 100644 index 0000000000..ae13a32936 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.html @@ -0,0 +1,151 @@ + + diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss new file mode 100644 index 0000000000..332d8ce52a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss @@ -0,0 +1,406 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-quick-link-panel .mat-mdc-dialog-surface { + border-radius: 14px; +} + +.tb-quick-link-panel.cdk-overlay-pane { + max-width: calc(100vw - 32px) !important; +} + +.tb-quick-link-dialog { + display: flex; + flex-direction: column; + gap: 14px; + box-sizing: border-box; + width: min(480px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + padding: 20px 20px 16px 24px; + overflow-y: auto; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + .mat-icon, tb-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + line-height: 20px; + } + + h2 { + margin: 0; + padding-right: 4px; + font: 500 17px/24px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0; + overflow-wrap: anywhere; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-quick-link-dialog-head { + display: flex; + align-items: center; + justify-content: space-between; + margin: -4px -8px -4px 0; + } + + .tb-quick-link-dialog-close.mat-mdc-icon-button, .tb-quick-link-clear.mat-mdc-icon-button { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .mat-mdc-button-touch-target { + width: 32px; + height: 32px; + } + } + + .tb-quick-link-dialog-tabs { + display: flex; + } + + .tb-quick-link-dialog-body { + display: flex; + flex-direction: column; + gap: 12px; + min-height: 0; + } + + .tb-quick-link-search { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + height: 40px; + padding: 0 4px 0 12px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.04); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + cursor: text; + + &:focus-within { + background: #fff; + box-shadow: 0 0 0 2px var(--tb-primary-500), 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); + color: var(--tb-primary-500); + } + + > .mat-icon { + color: inherit; + } + + input { + flex: 1; + min-width: 0; + height: 100%; + border: 0; + outline: 0; + background: transparent; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + caret-color: var(--tb-primary-500); + + &::placeholder { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + } + } + + .tb-quick-link-pages { + display: flex; + flex-direction: column; + max-height: 320px; + margin: 0 -8px; + overflow-y: auto; + } + + .tb-quick-link-page { + display: flex; + flex: none; + align-items: center; + gap: 10px; + box-sizing: border-box; + min-height: 40px; + padding: 7px 10px; + border-radius: 6px; + cursor: pointer; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + tb-icon { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + &.active { + background: rgba(0, 0, 0, 0.04); + } + + b { + font-weight: 600; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &.taken { + cursor: default; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + tb-icon { + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + } + } + + .tb-quick-link-page-text { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + } + + .tb-quick-link-page-name { + overflow: hidden; + font-size: 14px; + line-height: 20px; + white-space: nowrap; + text-overflow: ellipsis; + } + + .tb-quick-link-page-crumb { + margin-top: 1px; + overflow: hidden; + font-size: 12px; + line-height: 16px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .tb-quick-link-page-added { + display: inline-flex; + align-items: center; + gap: 2px; + margin-left: auto; + font-size: 12px; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + line-height: 16px; + color: inherit; + } + } + + .tb-quick-link-pages-divider { + flex: none; + height: 1px; + margin: 6px 10px; + background: rgba(0, 0, 0, 0.08); + } + + .tb-quick-link-pages-more { + flex: none; + padding: 4px 10px 8px; + font-size: 12px; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + .tb-quick-link-pages-empty { + padding: 10px; + font-size: 13px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .tb-quick-link-field { + display: flex; + flex-direction: column; + gap: 6px; + + > label, .tb-quick-link-label { + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.25px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + } + + .tb-quick-link-input { + box-sizing: border-box; + height: 40px; + padding: 0 12px; + border: 0; + border-radius: 8px; + outline: 0; + background: rgba(0, 0, 0, 0.04); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + caret-color: var(--tb-primary-500); + + &::placeholder { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + &:focus, &:focus-within { + background: #fff; + box-shadow: 0 0 0 2px var(--tb-primary-500), 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); + } + } + + .tb-quick-link-box { + display: flex; + align-items: center; + gap: 10px; + cursor: text; + + > .mat-icon, > tb-icon { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + } + + .tb-quick-link-bare { + flex: 1; + min-width: 0; + height: 100%; + border: 0; + outline: 0; + background: transparent; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + caret-color: var(--tb-primary-500); + + &::placeholder { + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + } + + .tb-quick-link-icon-search { + height: 36px; + padding-right: 2px; + padding-left: 10px; + } + + .tb-quick-link-icons { + display: grid; + grid-template-columns: repeat(auto-fill, 36px); + gap: 4px; + max-height: 164px; + margin: -2px; + padding: 2px; + overflow-y: auto; + } + + .tb-quick-link-icon-option { + display: inline-flex; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + padding: 0; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &[aria-checked="true"] { + background: color-mix(in srgb, var(--tb-primary-500) 8%, #fff); + box-shadow: inset 0 0 0 2px var(--tb-primary-500); + color: var(--tb-primary-500); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + tb-icon { + color: inherit; + } + } + + .tb-quick-link-icon-status { + font-size: 12px; + line-height: 16px; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + } + + .tb-quick-link-where { + display: flex; + align-items: center; + gap: 6px; + min-height: 18px; + font-size: 12px; + line-height: 16px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; + color: inherit; + } + + b { + font-weight: 500; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + &.error { + color: var(--tb-sev-critical, #D12730); + } + } + + .tb-quick-link-note { + display: flex; + align-items: flex-start; + gap: 6px; + font-size: 12px; + line-height: 16px; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + line-height: 16px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &.warn { + color: #8a5a00; + + .mat-icon { + color: #b26a00; + } + } + } + + .tb-quick-link-dialog-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 12px; + + .mdc-button { + height: 36px; + padding: 0 14px; + border-radius: 8px; + } + + .mat-mdc-button { + --mat-button-text-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.ts new file mode 100644 index 0000000000..2a4c8b3984 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.ts @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterNextRender, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + Injector, + signal, + viewChild, + ViewEncapsulation +} from '@angular/core'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { ResourcesService } from '@core/services/resources.service'; +import { getMaterialIcons, splitIconName } from '@shared/models/icon.models'; +import { Subscription } from 'rxjs'; +import { DocumentationLink } from '@shared/models/user-settings.models'; +import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; +import { + parseQuickWebLink, + QUICK_LINK_ICONS, + QuickLinkDialogResult, + quickLinkIconFromUrl, + quickLinkNameFromUrl, + QuickLinkPage +} from '@home/pages/home-page/quick-links.models'; + +export interface QuickLinkDialogData { + pages: QuickLinkPage[]; + used: string[]; + editing?: DocumentationLink; +} + +type QuickLinkKind = 'page' | 'web'; + +const CRUMB_CAP = 8; +const ICON_RESULTS = 96; +const ICON_SIZE = 40; + +@Component({ + selector: 'tb-quick-link-dialog', + templateUrl: './quick-link-dialog.component.html', + styleUrls: ['./quick-link-dialog.component.scss'], + encapsulation: ViewEncapsulation.None, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class QuickLinkDialogComponent { + + readonly dialogRef = inject(MatDialogRef); + readonly data = inject(MAT_DIALOG_DATA); + + private resources = inject(ResourcesService); + private injector = inject(Injector); + + private pageInput = viewChild>('pageInput'); + private urlInput = viewChild>('urlInput'); + private pageList = viewChild>('pageList'); + private iconGrid = viewChild>('iconGrid'); + + readonly editing = !!this.data.editing; + + readonly kindOptions: HomeToggleOption[] = [ + {value: 'page', label: 'home.quick-links.page'}, + {value: 'web', label: 'home.quick-links.web-link'} + ]; + + readonly kind = signal(this.editing ? 'web' : 'page'); + + readonly query = signal(''); + readonly active = signal(0); + + private readonly used = new Set(this.data.used); + + readonly pageGroups = computed(() => { + const query = this.query().trim().toLowerCase(); + if (!query) { + return {groups: [this.data.pages], more: 0}; + } + const byName = this.data.pages.filter(page => page.name.toLowerCase().includes(query)); + let byCrumb = this.data.pages.filter(page => !page.name.toLowerCase().includes(query) && page.crumb.toLowerCase().includes(query)); + let more = 0; + if (byCrumb.length > CRUMB_CAP) { + more = byCrumb.length - CRUMB_CAP; + byCrumb = byCrumb.slice(0, CRUMB_CAP); + } + return {groups: [byName, byCrumb].filter(group => group.length), more}; + }); + + readonly freePages = computed(() => this.pageGroups().groups.flat().filter(page => !this.used.has(page.id))); + + readonly activePage = computed(() => { + const free = this.freePages(); + return free[Math.min(this.active(), free.length - 1)] ?? null; + }); + + readonly url = signal(this.data.editing?.link ?? ''); + readonly name = signal(this.data.editing?.name ?? ''); + readonly icon = signal(this.data.editing?.icon || 'link'); + private nameTouched = this.editing; + private iconTouched = this.editing; + + readonly parsed = computed(() => parseQuickWebLink(this.url())); + + readonly insecure = computed(() => this.parsed().url?.protocol === 'http:'); + + readonly canSubmit = computed(() => !!this.parsed().url && !!this.name().trim()); + + readonly iconQuery = signal(''); + private readonly iconResults = signal<{query: string; icons: string[]} | null>(null); + private iconSubscription: Subscription | null = null; + + readonly iconSearch = computed(() => { + const query = this.iconQuery().trim(); + if (!query) { + const chosen = this.icon(); + return {icons: QUICK_LINK_ICONS.includes(chosen) ? QUICK_LINK_ICONS : [chosen, ...QUICK_LINK_ICONS], total: -1}; + } + const results = this.iconResults(); + if (results?.query !== query) { + return {icons: [] as string[], total: null}; + } + return {icons: results.icons.slice(0, ICON_RESULTS), total: results.icons.length}; + }); + + constructor() { + this.focusPane(); + inject(DestroyRef).onDestroy(() => this.iconSubscription?.unsubscribe()); + } + + setKind(kind: QuickLinkKind): void { + this.kind.set(kind); + this.focusPane(); + } + + onQuery(value: string): void { + this.query.set(value); + this.active.set(0); + } + + clearQuery(): void { + this.onQuery(''); + this.pageInput()?.nativeElement.focus(); + } + + freeIndex(page: QuickLinkPage): number { + return this.freePages().indexOf(page); + } + + onPageKeydown(event: KeyboardEvent): void { + const count = this.freePages().length; + if (event.key === 'ArrowDown' && count) { + event.preventDefault(); + this.active.set((Math.min(this.active(), count - 1) + 1) % count); + this.scrollActive(); + } else if (event.key === 'ArrowUp' && count) { + event.preventDefault(); + this.active.set((Math.min(this.active(), count - 1) - 1 + count) % count); + this.scrollActive(); + } else if (event.key === 'Enter' && this.activePage()) { + event.preventDefault(); + this.addPage(this.activePage()); + } + } + + addPage(page: QuickLinkPage): void { + if (!this.used.has(page.id)) { + this.dialogRef.close({page}); + } + } + + onUrl(value: string): void { + this.url.set(value); + const url = this.parsed().url; + if (url && !this.nameTouched) { + this.name.set(quickLinkNameFromUrl(url)); + } + if (url && !this.iconTouched) { + this.icon.set(quickLinkIconFromUrl(url)); + } + } + + onName(value: string): void { + this.name.set(value); + this.nameTouched = !!value.trim(); + } + + onIconQuery(value: string): void { + this.iconQuery.set(value); + this.searchIcons(value.trim()); + } + + clearIconQuery(input: HTMLInputElement): void { + this.iconQuery.set(''); + input.focus(); + } + + private searchIcons(query: string): void { + this.iconSubscription?.unsubscribe(); + if (!query) { + return; + } + this.iconSubscription = getMaterialIcons(this.resources, ICON_RESULTS, true, query).subscribe( + chunks => this.iconResults.set({query, icons: chunks.flat().map(icon => icon.name)}) + ); + } + + pick(icon: string): void { + this.icon.set(icon); + this.iconTouched = true; + } + + onIconQueryKeydown(event: KeyboardEvent): void { + const icons = this.iconSearch().icons; + if (event.key === 'Enter') { + event.preventDefault(); + if (icons[0]) { + this.pick(icons[0]); + } + } else if (event.key === 'ArrowDown' && icons.length) { + event.preventDefault(); + this.focusChosenIcon(); + } + } + + onIconGridKeydown(event: KeyboardEvent, queryInput: HTMLInputElement): void { + const icons = this.iconSearch().icons; + const grid = this.iconGrid()?.nativeElement; + if (!icons.length || !grid) { + return; + } + const columns = Math.max(1, Math.floor((grid.clientWidth + 4) / ICON_SIZE)); + const steps: {[key: string]: number} = {ArrowRight: 1, ArrowLeft: -1, ArrowDown: columns, ArrowUp: -columns}; + const step = steps[event.key]; + if (step === undefined) { + return; + } + event.preventDefault(); + const at = Math.max(0, icons.indexOf(this.icon())); + if (event.key === 'ArrowUp' && at - columns < 0) { + queryInput.focus(); + return; + } + this.pick(icons[Math.min(icons.length - 1, Math.max(0, at + step))]); + this.focusChosenIcon(); + } + + iconLabel(icon: string): string { + return splitIconName(icon)[1].replace(/[_-]/g, ' '); + } + + iconTabIndex(icon: string, index: number): number { + const icons = this.iconSearch().icons; + return icon === this.icon() || (!icons.includes(this.icon()) && index === 0) ? 0 : -1; + } + + submit(): void { + const url = this.parsed().url; + const name = this.name().trim(); + if (url && name) { + this.dialogRef.close({web: {name, icon: this.icon(), link: url.href}}); + } + } + + onFieldKeydown(event: KeyboardEvent): void { + if (event.key === 'Enter') { + event.preventDefault(); + this.submit(); + } + } + + private focusPane(): void { + afterNextRender(() => (this.kind() === 'page' ? this.pageInput() : this.urlInput())?.nativeElement.focus(), {injector: this.injector}); + } + + private scrollActive(): void { + afterNextRender(() => this.pageList()?.nativeElement.querySelector('.tb-quick-link-page.active')?.scrollIntoView({block: 'nearest'}), + {injector: this.injector}); + } + + private focusChosenIcon(): void { + afterNextRender(() => this.iconGrid()?.nativeElement.querySelector('[tabindex="0"]')?.focus(), {injector: this.injector}); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html new file mode 100644 index 0000000000..9c0fb707dc --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html @@ -0,0 +1,91 @@ + + + + @if (loaded()) { + @if (editing()) { + + } @else { + + } + } + + @if (loaded()) { + @if (editing()) { + + + + } @else { + + @if (!links().length) { + + } + } + } + diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss new file mode 100644 index 0000000000..370e29baf9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss @@ -0,0 +1,272 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-tiles'; +@use './home-table'; + +:host { + --tb-home-card-hideable-top: 20px; + display: block; + min-width: 0; + container-type: inline-size; +} + +@container (min-width: 300px) { + .tb-quick-links-columns:not(.fit-one) { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + column-gap: 16px; + clip-path: inset(0 -8px 1px -8px); + + > .tb-quick-link { + position: relative; + min-width: 0; + + &::before { + content: ""; + position: absolute; + right: 8px; + bottom: 0; + left: 8px; + border-bottom: 1px solid var(--tb-line-soft, rgba(0, 0, 0, 0.05)); + pointer-events: none; + } + } + } +} + +@container (min-width: 600px) { + .tb-quick-links-columns:not(.fit-one) { + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + } +} + +.tb-quick-links-edit.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.tb-quick-links-done.mdc-button { + height: 32px; + padding: 0 16px; + border-radius: 4px; +} + +.tb-quick-links-list { + display: flex; + flex-direction: column; + margin: 0 -8px; + + > .tb-home-empty-note { + padding: 4px 8px; + } +} + +.tb-quick-link { + display: flex; + align-items: center; + gap: 12px; + box-sizing: border-box; + height: 40px; + padding: 0 8px; + border: none; + border-radius: 6px; + background: transparent; + text-align: left; + text-decoration: none; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + &:hover { + border: none; + background: rgba(0, 0, 0, 0.04); + + .tb-quick-link-ext { + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: -2px; + } +} + +.tb-quick-link-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + line-height: 20px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-quick-link-text { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.mat-icon.tb-quick-link-ext { + flex: none; + width: 14px; + height: 14px; + margin-left: -8px; + font-size: 14px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.editing .tb-quick-links-list { + gap: 4px; +} + +.tb-quick-link-editing { + gap: 10px; + padding: 0 4px; + background: rgba(0, 0, 0, 0.03); + cursor: grab; + + &:hover { + background: rgba(0, 0, 0, 0.03); + } + + &.cdk-drag-placeholder { + opacity: 0.4; + } +} + +.tb-quick-link-drag { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.tb-quick-link-action { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + border-radius: 50%; + background: transparent; + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + cursor: pointer; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: inherit; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } +} + +.tb-quick-link-ext + .tb-quick-link-action, .tb-quick-link-text + .tb-quick-link-action { + margin-left: auto; +} + +.tb-quick-link-change:hover { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-quick-link-remove:hover { + color: var(--tb-sev-critical, #D12730); +} + +.tb-quick-links-add { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + width: 100%; + height: 40px; + padding: 0 12px; + border: 1px dashed rgba(0, 0, 0, 0.2); + border-radius: 8px; + background: none; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.2px; + text-align: left; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + cursor: pointer; + transition: border-color .2s, color .2s, background-color .2s; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: inherit; + } + + &:hover:not(:disabled) { + border-color: var(--tb-primary-500); + background: color-mix(in srgb, var(--tb-primary-500) 4%, #fff); + color: var(--tb-primary-500); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + } + + &:disabled { + border-style: solid; + border-color: rgba(0, 0, 0, 0.06); + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + cursor: default; + } +} + +.tb-quick-links-edit-footer { + display: flex; + align-items: center; + gap: 8px; + font: 400 12px/16px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-muted, rgba(0, 0, 0, 0.56)); + + .mat-mdc-button { + --mat-button-text-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + margin-left: -8px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.cdk-drag-preview.tb-quick-link-editing { + box-sizing: border-box; + border-radius: 6px; + background: #fff; + box-shadow: 0 4px 12px rgba(16, 24, 40, 0.16); +} + +.cdk-drop-list-dragging .tb-quick-link-editing:not(.cdk-drag-placeholder) { + transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts new file mode 100644 index 0000000000..7000b2d253 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterNextRender, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + Injector, + signal, + viewChild +} from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { MatDialog } from '@angular/material/dialog'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { map } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { UserSettingsService } from '@core/http/user-settings.service'; +import { MenuService } from '@core/services/menu.service'; +import { MenuSection } from '@core/services/menu.models'; +import { UtilsService } from '@core/services/utils.service'; +import { ToastNotificationService } from '@core/services/toast-notification.service'; +import { WhiteLabelingService } from '@core/http/white-labeling.service'; +import { DocumentationLink, HomeCardId, QuickLinks } from '@shared/models/user-settings.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { + defaultQuickLinks, + isQuickWebLinkId, + QUICK_LINKS_MAX, + QuickLinkDialogResult, + quickLinkPages, + QuickLinkView, + quickWebLinkId +} from '@home/pages/home-page/quick-links.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; +import { + QuickLinkDialogComponent, + QuickLinkDialogData +} from '@home/pages/home-page/components/quick-link-dialog.component'; + +@Component({ + selector: 'tb-quick-links-home', + templateUrl: './quick-links-home.component.html', + styleUrls: ['./quick-links-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class QuickLinksHomeComponent { + + readonly card = HOME_CARDS[HomeCardId.QUICK_LINKS]; + readonly max = QUICK_LINKS_MAX; + + private store = inject(Store); + private userSettingsService = inject(UserSettingsService); + private menuService = inject(MenuService); + private utils = inject(UtilsService); + private translate = inject(TranslateService); + private toast = inject(ToastNotificationService); + private dialog = inject(MatDialog); + private docsUrl = inject(WhiteLabelingService).getDocsUrl(); + private host = inject>(ElementRef); + private injector = inject(Injector); + + private columns = viewChild>('columns'); + + private readonly settings = signal(null); + + readonly editing = signal(false); + + readonly pages = toSignal(this.menuService.menuSections().pipe( + map(sections => quickLinkPages(sections, section => this.sectionName(section))) + ), {initialValue: []}); + + readonly loaded = computed(() => this.settings() !== null); + + readonly links = computed(() => { + const settings = this.settings(); + const pages = this.pages(); + const views: QuickLinkView[] = []; + for (const id of settings?.links ?? []) { + if (isQuickWebLinkId(id)) { + const web = settings.webLinks?.[id]; + if (web) { + views.push({id, name: web.name, icon: web.icon || 'link', web}); + } + } else { + const page = pages.find(p => p.id === id); + if (page) { + views.push({id, name: page.name, icon: page.icon, page}); + } + } + } + return views; + }); + + readonly full = computed(() => this.links().length >= QUICK_LINKS_MAX); + + constructor() { + this.userSettingsService.getQuickLinks().subscribe(quickLinks => this.settings.set(this.withDefaults(quickLinks))); + effect(() => { + this.links(); + this.editing(); + afterNextRender(() => this.fitColumns(), {injector: this.injector}); + }); + const observer = new ResizeObserver(() => this.fitColumns()); + observer.observe(this.host.nativeElement); + inject(DestroyRef).onDestroy(() => observer.disconnect()); + } + + toggleEdit(): void { + this.editing.set(!this.editing()); + } + + addLink(): void { + this.openDialog().subscribe(result => { + if (!result) { + return; + } + const settings = this.current(); + if ('page' in result) { + this.save({...settings, links: [...settings.links, result.page.id]}); + this.notify('home.quick-links.added', result.page.name); + } else { + const id = quickWebLinkId(); + this.save({links: [...settings.links, id], webLinks: {...settings.webLinks, [id]: result.web}}); + this.notify('home.quick-links.added', result.web.name); + } + }); + } + + editLink(link: QuickLinkView): void { + this.openDialog(link.web).subscribe(result => { + if (result && 'web' in result) { + const settings = this.current(); + this.save({...settings, webLinks: {...settings.webLinks, [link.id]: result.web}}); + this.notify('home.quick-links.saved', result.web.name); + } + }); + } + + remove(link: QuickLinkView): void { + const settings = this.current(); + const webLinks = {...settings.webLinks}; + delete webLinks[link.id]; + this.save({links: settings.links.filter(id => id !== link.id), webLinks}); + this.notify('home.quick-links.removed', link.name); + } + + drop(event: CdkDragDrop): void { + if (event.previousIndex === event.currentIndex) { + return; + } + const visible = this.links().map(link => link.id); + const [moved] = visible.splice(event.previousIndex, 1); + visible.splice(event.currentIndex, 0, moved); + const settings = this.current(); + this.save({...settings, links: [...visible, ...settings.links.filter(id => !visible.includes(id))]}); + } + + reset(): void { + this.settings.set(this.withDefaults({})); + this.userSettingsService.updateQuickLinks({links: null, webLinks: null}).subscribe(); + this.toast.dispatchNotification(this.toastConfig(this.translate.instant('home.quick-links.reset-done'))); + } + + private fitColumns(): void { + const list = this.columns()?.nativeElement; + if (!list) { + return; + } + list.classList.remove('fit-one'); + const cut = Array.from(list.querySelectorAll('.tb-quick-link-text')).some(text => text.scrollWidth > text.clientWidth + 1); + list.classList.toggle('fit-one', cut); + } + + private openDialog(editing?: DocumentationLink) { + return this.dialog.open(QuickLinkDialogComponent, { + panelClass: 'tb-quick-link-panel', + autoFocus: false, + restoreFocus: true, + data: { + pages: this.pages(), + used: this.links().filter(link => !!link.page).map(link => link.id), + editing + } + }).afterClosed(); + } + + private current(): Required { + const settings = this.settings(); + return {links: [...(settings?.links ?? [])], webLinks: {...(settings?.webLinks ?? {})}}; + } + + private save(quickLinks: QuickLinks): void { + this.settings.set(quickLinks); + this.userSettingsService.updateQuickLinks(quickLinks).subscribe(); + } + + private withDefaults(quickLinks: QuickLinks | null): QuickLinks { + if (quickLinks?.links) { + return quickLinks; + } + return defaultQuickLinks(getCurrentAuthUser(this.store)?.authority, this.docsUrl, key => this.translate.instant(key)); + } + + private sectionName(section: MenuSection): string { + return section.customTranslate ? this.utils.customTranslation(section.name, section.name) : this.translate.instant(section.name); + } + + private notify(key: string, name: string): void { + this.toast.dispatchNotification(this.toastConfig(this.translate.instant(key, {name}))); + } + + private toastConfig(message: string) { + return homeToast(message); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.scss new file mode 100644 index 0000000000..aeba5d4a37 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.scss @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; +} + +.tb-status-line { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px 8px; + margin-top: 12px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-pill { + display: inline-flex; + align-items: center; + gap: 8px; + height: 32px; + padding: 0 14px; + border-radius: 16px; + background: var(--tb-surface, #fff); + box-shadow: var(--tb-home-card-shadow); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0; + white-space: nowrap; + transition: box-shadow .15s ease; + + &:has(.tb-status-link:hover) { + box-shadow: var(--tb-home-card-shadow), 0 4px 12px -4px rgba(20, 52, 58, 0.14); + } +} + +.tb-status-link { + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + border-bottom: none; + + &:hover, &:focus, &:active { + border-bottom: none; + } + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 4px; + } +} + +.tb-status-dot { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.warn .tb-status-dot { + background: rgb(246, 103, 22); +} + +.tb-status-line-reserved { + min-height: 32px; +} + +.tb-status-line-in { + animation: tb-status-line-in .2s ease both; + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes tb-status-line-in { + from { + opacity: 0; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts new file mode 100644 index 0000000000..896074e584 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts @@ -0,0 +1,363 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, NgZone, signal, WritableSignal } from '@angular/core'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser, selectPersistDeviceStateToTelemetry } from '@core/auth/auth.selectors'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { AlarmCountCmd, EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityType } from '@shared/models/entity-type.models'; +import { EntityKeyType, EntityKeyValueType, FilterPredicateType, BooleanOperation, KeyFilter } from '@shared/models/query/query.models'; +import { AlarmSearchStatus, AlarmSeverity } from '@shared/models/alarm.models'; +import { Authority } from '@shared/models/authority.enum'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { AdminService } from '@core/http/admin.service'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; +import { TranslateService } from '@ngx-translate/core'; +import { FeaturesInfo } from '@shared/models/settings.models'; +import { SubscriptionInfo } from '@shared/models/subscription.models'; +import { of } from 'rxjs'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { catchError, take } from 'rxjs/operators'; + +type StatusKind = 'crit' | 'warn' | 'ok'; + +interface StatusPart { + key: string; + params?: Record; + cards?: HomeCardId[]; + link?: string; +} + +type SystemMetric = 'cpu' | 'ram' | 'disk'; + +interface SystemLoad { + metric: SystemMetric; + value: number; + services: string[]; +} + +interface ClusterService { + serviceId: string; + cpuUsage: number; + memoryUsage: number; + discUsage: number; +} + +const SYSTEM_KEYS = ['cpuUsage', 'memoryUsage', 'discUsage', 'clusterMode', 'clusterSystemData']; +const METRIC_KEYS: Record = {cpu: 'cpuUsage', ram: 'memoryUsage', disk: 'discUsage'}; +const METRIC_NAMES: Record = {cpu: 'CPU', ram: 'RAM', disk: 'Disk'}; +const LICENSE_NEAR = 0.85; +const WARN_LOAD = 75; +const CRIT_LOAD = 85; + +const loadLevel = (value: number): StatusKind => value > CRIT_LOAD ? 'crit' : value > WARN_LOAD ? 'warn' : 'ok'; + +@Component({ + selector: 'tb-status-line-home', + template: ` + @if (parts().length) { +
+ @for (part of parts(); track part.key; let first = $first) { + + @if (first) { + @if (kind() === 'crit') { + + } @else { + + } + } + @if (part.link || part.cards) { + {{ part.key | translate: part.params }} + } @else { + {{ part.key | translate: part.params }} + } + + } +
+ } @else if (reserve && !resolved()) { + + } + `, + styleUrls: ['./status-line-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class StatusLineHomeComponent { + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private router = inject(Router); + private store = inject(Store); + + private translate = inject(TranslateService); + + private readonly authority = getCurrentAuthUser(this.store)?.authority; + private readonly customer = this.authority === Authority.CUSTOMER_USER; + readonly sysAdmin = this.authority === Authority.SYS_ADMIN; + private readonly homePermissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); + private readonly canReadAlarms = !this.sysAdmin && this.homePermissions.canReadAlarms(); + private readonly canReadDevices = !this.sysAdmin && this.homePermissions.canReadEntities(EntityType.DEVICE); + private readonly devicesLink = this.canReadDevices ? this.homePermissions.entitiesLink(EntityType.DEVICE) : null; + + private readonly shownKey = `tb-home-status-line:${getCurrentAuthUser(this.store)?.userId}`; + + readonly reserve = this.authority !== Authority.TENANT_ADMIN || this.wasShown(); + + private systemLoad = signal(null); + private subscription = signal(undefined); + private features = signal(undefined); + private tenants = signal(null); + + private critical = signal(null); + private active = signal(null); + private devices = signal(null); + private inactive = signal(null); + + private subscribers: TelemetrySubscriber[] = []; + + readonly parts = computed(() => this.sysAdmin ? this.sysAdminParts() : this.tenantParts()); + + readonly resolved = computed(() => this.sysAdmin + ? !!this.systemLoad() && this.subscription() !== undefined && this.tenants() !== null + : [this.critical(), this.active(), this.devices(), this.inactive()].every(value => value !== null)); + + readonly kind = computed(() => this.sysAdmin ? this.sysAdminKind() : this.critical() ? 'crit' : this.inactive() ? 'warn' : 'ok'); + + private tenantParts(): StatusPart[] { + const critical = this.canReadAlarms ? this.critical() : 0; + const active = this.canReadAlarms ? this.active() : 0; + const devices = this.canReadDevices ? this.devices() : 0; + const inactive = this.canReadDevices ? this.inactive() : 0; + if (critical === null || active === null || devices === null || inactive === null) { + return []; + } + if (!devices) { + return this.customer && this.canReadDevices ? [{key: 'home.status.nothing-assigned'}] : []; + } + const parts: StatusPart[] = []; + if (this.canReadAlarms) { + if (critical) { + parts.push({key: 'home.status.critical-alarms', params: {count: critical}, cards: [HomeCardId.ALARMS], link: '/alarms'}); + } else if (active) { + parts.push({key: 'home.status.active-alarms', params: {count: active}, cards: [HomeCardId.ALARMS], link: '/alarms'}); + } else { + parts.push({key: 'home.status.no-alarms'}); + } + } + if (inactive) { + parts.push({key: 'home.status.inactive-devices', params: {count: inactive}, cards: [HomeCardId.DEVICES], link: this.devicesLink}); + } else { + parts.push({key: devices === 1 ? 'home.status.device-active' : 'home.status.all-devices-active', params: {count: devices}}); + } + return parts; + } + + private sysAdminParts(): StatusPart[] { + const load = this.systemLoad(); + const subscription = this.subscription(); + const features = this.features(); + const tenants = this.tenants(); + if (!load || subscription === undefined || tenants === null) { + return []; + } + const parts: StatusPart[] = []; + if (loadLevel(load.value) === 'ok') { + parts.push({key: 'home.status.system-ok'}); + } else { + const params = {name: METRIC_NAMES[load.metric], value: Math.round(load.value)}; + if (!load.services.length) { + parts.push({key: 'home.status.system-high', params, cards: [HomeCardId.SYSTEM_STATUS]}); + } else if (load.services.length === 1) { + parts.push({key: 'home.status.system-high-on', params: {...params, service: load.services[0]}, cards: [HomeCardId.SYSTEM_STATUS]}); + } else { + parts.push({key: 'home.status.system-high-services', params: {...params, count: load.services.length}, cards: [HomeCardId.SYSTEM_STATUS]}); + } + } + const near = this.licenseNear(subscription); + if (near.length) { + parts.push({key: 'home.status.license-near', params: {items: near.join(', ')}, cards: [HomeCardId.LICENSE], link: '/license'}); + } + if (!tenants) { + parts.push({key: 'home.status.no-tenants', cards: [HomeCardId.GET_STARTED_SYS_ADMIN], link: '/tenants'}); + } else if (features) { + const off = [features.whiteLabelingEnabled, features.emailEnabled, + features.smsEnabled, features.notificationEnabled, features.oauthEnabled, features.twoFaEnabled].filter(enabled => !enabled).length; + if (off) { + parts.push({key: 'home.status.features-off', params: {count: off}, + cards: [HomeCardId.GET_STARTED_SYS_ADMIN, HomeCardId.INSTALL_ITEMS]}); + } + } + return parts; + } + + private sysAdminKind(): StatusKind { + const load = this.systemLoad(); + const level = load ? loadLevel(load.value) : 'ok'; + if (level === 'crit') { + return 'crit'; + } + const subscription = this.subscription(); + return level === 'warn' || (subscription && this.licenseNear(subscription).length) ? 'warn' : 'ok'; + } + + private licenseNear(subscription: SubscriptionInfo | null): string[] { + if (!subscription) { + return []; + } + const items: [string, number, number][] = [ + ['home.status.license-devices', subscription.devicesCount, subscription.maxDevices], + ['home.status.license-assets', subscription.assetsCount, subscription.maxAssets], + ['home.status.license-ai-credits', subscription.usedAiCredits, subscription.maxAiCredits] + ]; + return items.filter(([, used, max]) => max > 0 && (used ?? 0) / max >= LICENSE_NEAR) + .map(([key, used, max]) => this.translate.instant(key, {percent: Math.round(used / max * 100)})); + } + + constructor() { + this.destroyRef.onDestroy(() => this.subscribers.forEach(subscriber => subscriber.unsubscribe())); + effect(() => { + if (this.resolved()) { + this.rememberShown(this.parts().length > 0); + } + }); + if (this.sysAdmin) { + this.watchSysAdmin(); + } else { + this.watchTenant(); + } + } + + private watchTenant(): void { + this.store.select(selectPersistDeviceStateToTelemetry).pipe(take(1)).subscribe(persisted => { + const activeKeyType = persisted ? EntityKeyType.TIME_SERIES : EntityKeyType.SERVER_ATTRIBUTE; + if (this.canReadAlarms) { + this.countAlarms(this.critical, [AlarmSeverity.CRITICAL]); + this.countAlarms(this.active); + } + if (!this.canReadDevices) { + return; + } + this.countDevices(this.devices); + this.countDevices(this.inactive, [{ + key: {type: activeKeyType, key: 'active'}, + valueType: EntityKeyValueType.BOOLEAN, + predicate: { + type: FilterPredicateType.BOOLEAN, + operation: BooleanOperation.EQUAL, + value: {defaultValue: false} + } + }]); + }); + } + + private wasShown(): boolean { + return readStored(this.shownKey) === '1'; + } + + private rememberShown(shown: boolean): void { + writeStored(this.shownKey, shown ? '1' : '0'); + } + + open(part: StatusPart): void { + const card = (part.cards ?? []).map(id => document.querySelector(`[data-home-card="${id}"]`)).find(element => !!element); + if (card) { + card.scrollIntoView({behavior: 'smooth', block: 'center'}); + } else if (part.link) { + this.router.navigateByUrl(part.link); + } + } + + private countAlarms(target: WritableSignal, severityList?: AlarmSeverity[]): void { + const cmd = new AlarmCountCmd(); + cmd.query = { + entityFilter: null, + statusList: [AlarmSearchStatus.ACTIVE], + ...(severityList ? {severityList} : {}) + }; + const subscriber = this.subscribe(cmd); + subscriber.alarmCount$.subscribe(update => target.set(update.count ?? 0)); + subscriber.subscribe(); + } + + private watchSysAdmin(): void { + const adminService = inject(AdminService); + const config = {ignoreErrors: true, ignoreLoading: true}; + adminService.getSubscriptionInfo(config).pipe(catchError(() => of(null))).subscribe(info => this.subscription.set(info)); + const sysAdminHome = inject(SysAdminHomeService, {optional: true}); + (sysAdminHome ? sysAdminHome.featuresInfo$ : adminService.getFeaturesInfo(config).pipe(catchError(() => of(null)))) + .subscribe(info => this.features.set(info)); + this.countEntities(this.tenants, EntityType.TENANT); + const keys = SYSTEM_KEYS.map(key => ({type: EntityKeyType.TIME_SERIES, key})); + const cmd = new EntityDataCmd(); + cmd.query = { + entityFilter: {type: AliasFilterType.apiUsageState}, + pageLink: {page: 0, pageSize: 1}, + entityFields: [], + latestValues: keys + }; + cmd.latestCmd = {keys}; + const values: Record = {}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + this.subscribers.push(subscriber); + subscriber.entityData$.subscribe(update => { + const entity = (update.data?.data ?? update.update ?? [])[0]; + SYSTEM_KEYS.forEach(key => { + const latest = entity?.latest?.[EntityKeyType.TIME_SERIES]?.[key]; + if (latest?.ts) { + values[key] = latest.value; + } + }); + if (entity || update.data) { + this.systemLoad.set(this.toSystemLoad(values)); + } + }); + subscriber.subscribe(); + } + + private toSystemLoad(values: Record): SystemLoad { + const metrics = Object.keys(METRIC_KEYS) as SystemMetric[]; + if (values.clusterMode === 'true' && values.clusterSystemData) { + let services: ClusterService[] = []; + try { + services = JSON.parse(values.clusterSystemData); + } catch { + services = []; + } + if (services.length) { + const loads = metrics.flatMap(metric => services.map(service => + ({metric, value: Number(service[METRIC_KEYS[metric]]) || 0, service: service.serviceId}))); + const worst = loads.reduce((top, load) => load.value > top.value ? load : top); + return { + metric: worst.metric, + value: worst.value, + services: loads.filter(load => load.metric === worst.metric && load.value === worst.value).map(load => load.service) + }; + } + } + return metrics.map(metric => ({metric, value: Number(values[METRIC_KEYS[metric]]) || 0, services: []})) + .reduce((top, load) => load.value > top.value ? load : top); + } + + private countDevices(target: WritableSignal, keyFilters?: KeyFilter[]): void { + this.countEntities(target, EntityType.DEVICE, keyFilters); + } + + private countEntities(target: WritableSignal, entityType: EntityType, keyFilters?: KeyFilter[]): void { + this.homeCounts.watchEntityCount(entityType, count => target.set(count), this.destroyRef, keyFilters); + } + + private subscribe(cmd: AlarmCountCmd): TelemetrySubscriber { + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + this.subscribers.push(subscriber); + return subscriber; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html new file mode 100644 index 0000000000..228bb5a5cc --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.html @@ -0,0 +1,102 @@ + + + @if (loaded()) { + {{ cluster() ? ('home.system.services' | translate: {count: services().length}) : ('home.system.last-hour' | translate) }} + } + + @if (update(); as info) { + + @if (info.currentVersionReleaseNotesUrl) { + {{ 'home.system.version' | translate: {version: info.currentVersion} }} + } @else { + {{ 'home.system.version' | translate: {version: info.currentVersion} }} + } + @if (releaseHidden()) { + + } + + } + + @if (loaded()) { + @if (cluster()) { +
+ + + + + + @for (metric of metrics; track metric.id) { + + } + + + + @for (service of shownServices(); track service.serviceId) { + + + + @for (metric of metrics; track metric.id) { + @let figLevel = serviceLevel(service, metric.id); + + } + + } + +
+ + + + + +
{{ service.serviceId }}{{ service.serviceType }} + + @if (figLevel) { + {{ figLevel === 'crit' ? 'error' : 'warning' }} + } + {{ serviceValue(service, metric.id) }}% + +
+
+ + } @else { +
+ @for (gauge of gauges(); track gauge.id) { +
+
+ {{ gauge.label | translate }} + @if (gauge.level) { + {{ gauge.level === 'crit' ? 'error' : 'warning' }} + } +
+
{{ gauge.value | number: '1.0-0' }}%{{ gauge.total }}
+
+ } +
+ + } + @if (callout(); as note) { +
+ {{ note.level === 'crit' ? 'error_outline' : 'warning_amber' }} + {{ note.title }}. {{ note.text }} +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss new file mode 100644 index 0000000000..9f1dfb1fd2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.scss @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './home-table'; + +:host { + display: block; + min-width: 0; +} + +.tb-system-period { + margin-left: 4px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-system-version { + display: inline-flex; + align-items: baseline; + gap: 8px; + white-space: nowrap; +} + +.tb-system-version-link { + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + text-decoration: none; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + &, &:hover, &:focus, &:active { + border-bottom: none; + } + + &:is(a):hover { + text-decoration: underline; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } +} + +.tb-system-version-new { + padding: 0; + border: 0; + background: none; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-primary-500); + cursor: pointer; + + &::before { + content: "·"; + margin-right: 8px; + font-weight: 400; + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); + } + + &:hover { + text-decoration: underline; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 2px; + } +} + +.tb-system-gauges { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} + +.tb-system-gauge { + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; + min-width: 0; + padding: 8px 12px 10px; + border: 1px solid rgba(0, 0, 0, 0.10); + border-radius: 10px; + background: #fff; + + &.warn .tb-system-gauge-count { + color: #955400; + } + + &.crit .tb-system-gauge-count { + color: var(--tb-sev-critical, #D12730); + } + + &.crit .tb-system-gauge-mark { + color: var(--tb-sev-critical, #D12730); + } +} + +.tb-system-gauge-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.tb-system-gauge-title { + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0.1px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-system-key { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; +} + +.tb-system-gauge-mark.mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: #b26500; +} + +.tb-system-gauge-count { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 6px; + font: 500 20px/28px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + font-variant-numeric: tabular-nums; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.tb-system-gauge-total { + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + white-space: nowrap; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); +} + +.tb-system-chart { + height: 130px; +} + +.tb-system-services-wrap.scrolling { + max-height: calc(32px + var(--tb-system-rows) * 36px); + overflow-y: auto; + scrollbar-width: thin; + + thead th { + position: sticky; + top: 0; + z-index: 1; + background: var(--tb-surface, #fff); + } +} + +.tb-system-services { + table-layout: auto; + + tbody tr { + cursor: default; + } + + .col-service { + width: 99%; + max-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + + td.col-type { + font-size: 13px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .col-num { + width: 64px; + text-align: right; + } + + th.col-num .th-label { + flex-direction: row-reverse; + } +} + +.tb-system-mono { + font-family: 'Roboto Mono', monospace; + font-size: 13px; +} + +.tb-system-fig { + display: inline-flex; + align-items: center; + gap: 2px; + font-variant-numeric: tabular-nums; + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + color: inherit; + } + + &.warn { + color: #955400; + } + + &.crit { + font-weight: 500; + color: var(--tb-sev-critical, #D12730); + } +} + +.tb-system-callout { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + border-radius: 8px; + font: 400 13px/18px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + > .mat-icon { + flex: none; + width: 20px; + height: 20px; + font-size: 20px; + } + + > span { + flex: 1; + min-width: 0; + } + + &.crit { + background: rgba(209, 39, 48, 0.04); + + > .mat-icon { + color: var(--tb-sev-critical, #D12730); + } + } + + &.warn { + background: rgb(255 167 38 / 0.16); + + > .mat-icon { + color: #b26500; + } + } +} + +@container tb-home (max-width: 599px) { + .tb-system-services .col-type { + display: none; + } + + .tb-system-gauge { + padding-right: 8px; + padding-left: 8px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts new file mode 100644 index 0000000000..7f6ef72e8f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts @@ -0,0 +1,459 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + afterRenderEffect, + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + ElementRef, + inject, + NgZone, + Renderer2, + signal, + viewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import * as echarts from 'echarts/core'; +import { CallbackDataParams } from 'echarts/types/dist/shared'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; +import { AggregationType, HOUR, MINUTE } from '@shared/models/time/time.models'; +import { UpdateMessage } from '@shared/models/settings.models'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; +import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; +import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } from '@home/pages/home-page/home-chart.models'; + +type SystemMetric = 'cpu' | 'ram' | 'disk'; +type SystemLevel = 'crit' | 'warn' | ''; +type ServiceSortKey = 'serviceId' | 'serviceType' | SystemMetric; + +interface MetricConfig { + id: SystemMetric; + key: string; + label: string; + color: string; +} + +interface ClusterService { + serviceId: string; + serviceType: string; + cpuUsage: number; + cpuCount: number; + memoryUsage: number; + totalMemory: number; + discUsage: number; + totalDiscSpace: number; +} + +interface SystemWorst { + metric: SystemMetric; + value: number; + level: SystemLevel; + services: string[]; +} + +const METRICS: MetricConfig[] = [ + {id: 'cpu', key: 'cpuUsage', label: 'widgets.system-info.cpu', color: '#305680'}, + {id: 'ram', key: 'memoryUsage', label: 'widgets.system-info.ram', color: '#9c27b0'}, + {id: 'disk', key: 'discUsage', label: 'widgets.system-info.disk', color: '#26a69a'} +]; + +const SERVICE_KEYS: Record = {cpu: 'cpuUsage', ram: 'memoryUsage', disk: 'discUsage'}; +const LATEST_KEYS = ['clusterMode', 'clusterSystemData', 'cpuUsage', 'cpuCount', 'memoryUsage', 'totalMemory', 'discUsage', 'totalDiscSpace']; +const LABEL_STEP = 15 * MINUTE; +const LOADING_HEIGHT = 304; +const SERVICES_PREVIEW = 8; +const SERVICES_SLACK = 2; +const SERVICES_LIMIT = 20; +const AXIS_LABEL = {color: 'rgba(0, 0, 0, 0.56)', fontFamily: 'Roboto', fontSize: 12, fontWeight: 400, lineHeight: 16}; + +const GB = 1024 * 1024 * 1024; + +const gigabytes = (bytes: number): number => Math.round(bytes / GB); + +const level = (value: number): SystemLevel => value > 85 ? 'crit' : value > 75 ? 'warn' : ''; + +@Component({ + selector: 'tb-system-status-home', + templateUrl: './system-status-home.component.html', + styleUrls: ['./system-status-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class SystemStatusHomeComponent { + + readonly metrics = METRICS; + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private renderer = inject(Renderer2); + private translate = inject(TranslateService); + private host = inject>(ElementRef); + private sysAdminHome = inject(SysAdminHomeService); + + private readonly latest = signal | null>(null); + private readonly history = signal>({cpu: [], ram: [], disk: []}); + private readonly window = signal({start: Date.now() - HOUR, end: Date.now()}); + + readonly servicesPreview = SERVICES_PREVIEW; + readonly servicesSlack = SERVICES_SLACK; + readonly servicesLimit = SERVICES_LIMIT; + + readonly expanded = signal(false); + + readonly update = signal(null); + readonly sort = signal<[ServiceSortKey, 'asc' | 'desc']>(['serviceId', 'asc']); + + readonly cluster = computed(() => this.latest()?.clusterMode === 'true'); + + readonly loaded = computed(() => this.latest() !== null); + + readonly cardDefinition = computed(() => { + const card = HOME_CARDS[HomeCardId.SYSTEM_STATUS]; + return this.loaded() ? card : {...card, height: LOADING_HEIGHT}; + }); + + readonly services = computed(() => { + const data = this.latest()?.clusterSystemData; + if (!this.cluster() || !data) { + return []; + } + try { + return JSON.parse(data); + } catch { + return []; + } + }); + + readonly sortedServices = computed(() => { + const [key, direction] = this.sort(); + const value = (service: ClusterService) => key === 'serviceId' || key === 'serviceType' ? service[key] : service[SERVICE_KEYS[key]]; + return [...this.services()].sort((a, b) => { + const first = value(a); + const second = value(b); + return (first > second ? 1 : first < second ? -1 : 0) * (direction === 'asc' ? 1 : -1); + }); + }); + + readonly shownServices = computed(() => { + const services = this.sortedServices(); + if (this.expanded() || services.length <= SERVICES_PREVIEW + SERVICES_SLACK) { + return services; + } + return services.slice(0, SERVICES_PREVIEW); + }); + + readonly scrolling = computed(() => this.expanded() && this.services().length > SERVICES_LIMIT); + + readonly gauges = computed(() => { + const latest = this.latest() ?? {}; + const totals: Record = { + cpu: this.translate.instant('home.system.cores', {count: this.number(latest.cpuCount)}), + ram: this.translate.instant('home.system.gb', {value: gigabytes(this.number(latest.totalMemory))}), + disk: this.translate.instant('home.system.gb', {value: gigabytes(this.number(latest.totalDiscSpace))}) + }; + const totalValues: Record = { + cpu: 100, ram: this.number(latest.totalMemory), disk: this.number(latest.totalDiscSpace) + }; + return METRICS.map(metric => { + const value = this.number(latest[metric.key]); + return { + ...metric, + value, + level: level(value), + total: totals[metric.id], + tooltip: this.valueTooltip(metric.id, value, totalValues[metric.id]) + }; + }); + }); + + readonly worst = computed(() => { + if (!this.loaded()) { + return null; + } + let loads: {metric: SystemMetric; value: number; service?: string}[]; + if (this.cluster()) { + loads = this.services().flatMap(service => METRICS.map(metric => + ({metric: metric.id, value: Number(service[SERVICE_KEYS[metric.id]]) || 0, service: service.serviceId}))); + } else { + loads = this.gauges().map(gauge => ({metric: gauge.id, value: gauge.value})); + } + if (!loads.length) { + return null; + } + const top = loads.reduce((max, load) => load.value > max.value ? load : max); + return { + metric: top.metric, + value: top.value, + level: level(top.value), + services: loads.filter(load => load.service && load.metric === top.metric && load.value === top.value).map(load => load.service) + }; + }); + + readonly callout = computed(() => { + const worst = this.worst(); + if (!worst?.level) { + return null; + } + const name = this.metricName(worst.metric); + const value = Math.round(worst.value); + const title = worst.services.length + ? this.translate.instant('home.system.at-on', {name, value, services: worst.services.reduce((first, second) => this.translate.instant('home.system.and', {first, second}))}) + : this.translate.instant('home.system.at', {name, value}); + return {level: worst.level, title, text: this.levelText(worst.metric, worst.level).replace(/^[^.]+\.\s*/, '')}; + }); + + readonly releaseHidden = computed(() => { + const update = this.update(); + return !!update?.updateAvailable && this.sysAdminHome.hiddenRelease() === update.latestVersion; + }); + + private readonly chartElement = viewChild>('chart'); + + private chart: ECharts | null = null; + + constructor() { + this.sysAdminHome.update$.subscribe(update => this.update.set(update)); + const subscriber = this.subscribe(); + const tick = setInterval(() => this.window.set({start: Date.now() - HOUR, end: Date.now()}), MINUTE); + const resizeObserver = new ResizeObserver(() => this.chart?.resize()); + resizeObserver.observe(this.host.nativeElement); + afterRenderEffect(() => this.render()); + inject(DestroyRef).onDestroy(() => { + subscriber.unsubscribe(); + clearInterval(tick); + resizeObserver.disconnect(); + this.chart?.dispose(); + }); + } + + sortBy(key: ServiceSortKey): void { + const [current, direction] = this.sort(); + if (current === key) { + this.sort.set([key, direction === 'asc' ? 'desc' : 'asc']); + } else { + this.sort.set([key, key === 'serviceId' || key === 'serviceType' ? 'asc' : 'desc']); + } + } + + sortIcon(key: ServiceSortKey): string { + const [current, direction] = this.sort(); + return current === key && direction === 'desc' ? 'arrow_downward' : 'arrow_upward'; + } + + ariaSort(key: ServiceSortKey): string { + const [current, direction] = this.sort(); + return current === key ? (direction === 'asc' ? 'ascending' : 'descending') : 'none'; + } + + serviceValue(service: ClusterService, metric: SystemMetric): number { + return Math.round(Number(service[SERVICE_KEYS[metric]]) || 0); + } + + serviceLevel(service: ClusterService, metric: SystemMetric): SystemLevel { + return level(Number(service[SERVICE_KEYS[metric]]) || 0); + } + + serviceTooltip(service: ClusterService, metric: SystemMetric): string { + const total = metric === 'cpu' ? 100 : metric === 'ram' ? service.totalMemory : service.totalDiscSpace; + return this.valueTooltip(metric, Number(service[SERVICE_KEYS[metric]]) || 0, total); + } + + showRelease(): void { + this.sysAdminHome.setHiddenRelease(null); + setTimeout(() => document.querySelector('[data-home-card="productRelease"]')?.scrollIntoView({behavior: 'smooth', block: 'nearest'})); + } + + private subscribe(): TelemetrySubscriber { + const now = Date.now(); + const cmd = new EntityDataCmd(); + cmd.query = { + entityFilter: {type: AliasFilterType.apiUsageState}, + pageLink: {page: 0, pageSize: 1}, + entityFields: [], + latestValues: LATEST_KEYS.map(key => ({type: EntityKeyType.TIME_SERIES, key})) + }; + cmd.historyCmd = { + keys: METRICS.map(metric => metric.key), + startTs: now - HOUR, + endTs: now, + intervalType: IntervalType.MILLISECONDS, + interval: 1000, + timeZoneId: Intl.DateTimeFormat().resolvedOptions().timeZone, + limit: 1000, + agg: AggregationType.NONE + }; + cmd.latestCmd = {keys: LATEST_KEYS.map(key => ({type: EntityKeyType.TIME_SERIES, key}))}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + subscriber.entityData$.subscribe(update => { + const entity = (update.data?.data ?? update.update ?? [])[0]; + if (!entity) { + if (update.data) { + this.latest.set({}); + } + return; + } + const latest = {...(this.latest() ?? {})}; + LATEST_KEYS.forEach(key => { + const value = entity.latest?.[EntityKeyType.TIME_SERIES]?.[key]; + if (value?.ts) { + latest[key] = value.value; + } + }); + const history = {...this.history()}; + METRICS.forEach(metric => { + const points = new Map(history[metric.id]); + (entity.timeseries?.[metric.key] ?? []).forEach(value => points.set(value.ts, Number(value.value))); + const value = entity.latest?.[EntityKeyType.TIME_SERIES]?.[metric.key]; + if (value?.ts) { + points.set(value.ts, Number(value.value)); + } + history[metric.id] = [...points.entries()].filter(([, number]) => !isNaN(number)).sort((a, b) => a[0] - b[0]); + }); + this.history.set(history); + this.latest.set(latest); + this.window.set({start: Date.now() - HOUR, end: Date.now()}); + }); + subscriber.subscribe(); + return subscriber; + } + + private render(): void { + const element = this.chartElement()?.nativeElement; + const history = this.history(); + const window = this.window(); + if (!element) { + this.chart?.dispose(); + this.chart = null; + return; + } + echartsModule.init(); + if (this.chart && this.chart.getDom() !== element) { + this.chart.dispose(); + this.chart = null; + } + if (!this.chart) { + this.renderer.setStyle(element, 'letterSpacing', 'normal'); + this.chart = echarts.init(element, null, {renderer: 'svg'}); + } + this.chart.setOption(this.option(history, window), true); + } + + private option(history: Record, window: {start: number; end: number}): EChartsOption { + const span = window.end - window.start; + const series = METRICS.map(metric => ({ + metric, + points: history[metric.id].filter(([ts]) => ts >= window.start).map(([ts, value]) => [ts - window.start, value] as [number, number]) + })); + return { + backgroundColor: 'transparent', + tooltip: [{ + ...homeChartTooltipOptions, + formatter: (params: CallbackDataParams[]) => this.tooltip(params.filter(param => METRICS.some(metric => metric.id === param.seriesId)), + window.start) + }], + grid: [{left: 40, right: 12, top: 6, bottom: 26, containLabel: false}], + xAxis: [{ + type: 'value', + min: 0, + max: span, + interval: LABEL_STEP, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: false}, + axisLabel: { + ...AXIS_LABEL, + margin: 12, + showMinLabel: true, + showMaxLabel: true, + alignMinLabel: 'left', + alignMaxLabel: 'right', + formatter: (value: number) => this.xLabel(window.start, span, value) + } + }], + yAxis: [{ + type: 'value', + min: 0, + max: 100, + interval: 50, + axisLine: {show: false}, + axisTick: {show: false}, + splitLine: {show: true, lineStyle: {color: 'rgba(0, 0, 0, 0.06)', width: 1}}, + axisLabel: {...AXIS_LABEL, margin: 8, formatter: (value: number) => `${value}%`} + }], + series: series.flatMap(({metric, points}) => [{ + id: metric.id, + type: 'line' as const, + name: this.translate.instant(metric.label), + color: metric.color, + smooth: false, + showSymbol: false, + ...homeChartHoverSymbol(metric.color), + lineStyle: {width: 2, color: metric.color, cap: 'round' as const, join: 'round' as const}, + data: points + }, { + id: `${metric.id}-now`, + type: 'line' as const, + silent: true, + tooltip: {show: false}, + showSymbol: true, + symbol: 'circle', + symbolSize: 8, + z: 3, + itemStyle: {color: metric.color, borderColor: '#fff', borderWidth: 2}, + lineStyle: {width: 0}, + data: points.length ? [points[points.length - 1]] : [] + }]), + animation: false + }; + } + + private tooltip(params: CallbackDataParams[], start: number): string { + if (!params.length) { + return ''; + } + const date = new Date(Number(params[0].value[0]) + start); + const time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + return homeChartTooltipHtml(time, params.map(param => { + const metric = METRICS.find(item => item.id === param.seriesId); + return {color: metric.color, name: this.metricName(metric.id), value: `${Math.round(Number(param.value[1]))}%`}; + })); + } + + private xLabel(start: number, span: number, offset: number): string { + if (offset >= span - 1000) { + return this.translate.instant('home.system.now'); + } + if (offset > span - LABEL_STEP + MINUTE) { + return ''; + } + const date = new Date(start + offset); + return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + } + + private valueTooltip(metric: SystemMetric, value: number, total: number): string { + const rounded = Math.round(value); + const used = metric === 'cpu' ? `${rounded} / 100 %` : `${gigabytes(total * value / 100)} / ${gigabytes(total)} GB`; + const valueLevel = level(value); + return valueLevel ? `${used}\n\n${this.levelText(metric, valueLevel)}` : used; + } + + private levelText(metric: SystemMetric, valueLevel: SystemLevel): string { + return this.translate.instant(`widgets.system-info.${metric}-${valueLevel === 'crit' ? 'critical' : 'warning'}-text`); + } + + private metricName(metric: SystemMetric): string { + return this.translate.instant(`widgets.system-info.${metric}`); + } + + private number(value: string | undefined): number { + const number = Number(value); + return isFinite(number) ? number : 0; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.scss new file mode 100644 index 0000000000..6025d3c024 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.scss @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-ai-attn-block { + margin-top: 22px; + container-type: inline-size; +} + +.tb-ai-attn-block.appear { + animation: tb-ai-attn-in .25s ease-out; +} + +@keyframes tb-ai-attn-in { + from { + opacity: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-ai-attn-block.appear { + animation: none; + } +} + +.tb-ai-attn-block.reserve .tb-ai-attn-h { + color: var(--tb-ink-38, rgba(0, 0, 0, 0.38)); +} + +.tb-chat-pill.placeholder { + width: 200px; + pointer-events: none; +} + +.tb-chat-pill-skeleton { + flex: 1; + height: 12px; + border-radius: 4px; + background: linear-gradient(90deg, rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.09) 50%, rgba(0, 0, 0, 0.05) 100%) 0 0 / 200% 100%; + animation: tb-ai-attn-shimmer 1.4s ease-in-out infinite; +} + +@keyframes tb-ai-attn-shimmer { + from { + background-position: 100% 0; + } + to { + background-position: -100% 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-chat-pill-skeleton { + animation: none; + } +} + +.tb-ai-attn-h { + margin: 0 2px 6px; + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: .1px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.tb-ai-attn { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.tb-chat-pill { + &:hover, &:focus, &:active { + border-bottom: none; + } + + display: inline-flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + height: 40px; + max-width: 300px; + padding: 0 14px 0 12px; + border-radius: 12px; + background: var(--tb-surface, #fff); + box-shadow: var(--tb-home-card-shadow); + font: 500 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + text-decoration: none; + border-bottom: none; + transition: box-shadow .15s ease; + + &:hover, &:focus-visible { + outline: 0; + box-shadow: var(--tb-home-card-shadow), 0 4px 12px -4px rgba(20, 52, 58, 0.14); + } +} + +.tb-chat-pill-m { + flex: none; + margin-left: 2px; + font: 400 13px/20px var(--tb-font, Roboto, sans-serif); + font-variant-numeric: tabular-nums; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-chat-pill-t { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +@container (max-width: 560px) { + .tb-ai-attn { + flex-direction: column; + align-items: stretch; + } + + .tb-chat-pill { + width: 100%; + max-width: none; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts new file mode 100644 index 0000000000..e01fbb844d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, effect, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { interval } from 'rxjs'; +import { ChatInfo } from '@shared/models/ai-chat.models'; +import { homeAgo, homeElapsed } from '@home/pages/home-page/home-list.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiChatsService } from '@core/services/ai-chats.service'; + +const SHOWN = 2; + +const TICK_MS = 60_000; + +@Component({ + selector: 'tb-waiting-ai-chats-home', + template: ` + @if (!chats.statusResolved()) { + @if (reserved) { + + } + } @else if (waiting().length) { +
+
{{ 'home.ai.waiting' | translate }}
+
+ @for (chat of shown(); track chat.id) { + @let elapsed = elapsedOf(chat); + + + {{ chat.title || ('ai-assistant.new-chat' | translate) }} + @if (elapsed) { + {{ elapsed }} + } + + } +
+
+ } + `, + styleUrls: ['./waiting-ai-chats-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class WaitingAIChatsHomeComponent { + + readonly chats = inject(AiChatsService); + + private readonly translate = inject(TranslateService); + + private readonly now = signal(Date.now()); + + readonly waiting = computed(() => this.chats.statusChats().filter(chat => this.chats.needsAttention(chat)) + .sort((a, b) => (this.chats.levelOf(a) === 'error' ? 0 : 1) - (this.chats.levelOf(b) === 'error' ? 0 : 1))); + + readonly shown = computed(() => this.waiting().slice(0, SHOWN)); + + private readonly shownKey = `tb-home-waiting-chats:${getCurrentAuthUser(inject(Store))?.userId}`; + + readonly reserved = this.readShown(); + + readonly reservedPills = Array.from({length: this.reserved}, (_, i) => i); + + constructor() { + this.chats.watchStatus(); + interval(TICK_MS).pipe(takeUntilDestroyed()).subscribe(() => this.now.set(Date.now())); + effect(() => { + if (this.chats.statusResolved()) { + this.writeShown(this.shown().length); + } + }); + } + + elapsedOf(chat: ChatInfo): string | null { + return chat.updatedTime ? homeElapsed(this.translate, Math.max(0, this.now() - chat.updatedTime)) : null; + } + + agoOf(chat: ChatInfo): string { + return homeAgo(this.translate, Math.max(0, this.now() - chat.updatedTime)); + } + + private readShown(): number { + return Math.min(SHOWN, Math.max(0, Number(readStored(this.shownKey)) || 0)); + } + + private writeShown(count: number): void { + writeStored(this.shownKey, String(count)); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.scss new file mode 100644 index 0000000000..19f67cd243 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.scss @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + min-width: 0; +} + +.tb-home-kicker { + margin: 0 0 4px; + font: 500 12px/16px var(--tb-font, Roboto, sans-serif); + letter-spacing: .5px; + text-transform: uppercase; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); +} + +.tb-greeting { + margin: 0; + font: 600 28px/36px var(--tb-font, Roboto, sans-serif); + letter-spacing: -0.2px; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + + &.with-spark { + display: flex; + align-items: center; + gap: 10px; + } +} + +.tb-greeting .tb-greet-spark { + --m: 44px; + --ai-mark-ink-a: color-mix(in oklab, var(--tb-primary-500) 50%, var(--ai-mark-ink-c)); + --ai-mark-ink-b: color-mix(in oklab, var(--tb-primary-500) 20%, var(--ai-mark-ink-c)); + width: calc(var(--m) * var(--ai-spark)); + height: calc(var(--m) * var(--ai-spark)); + border-radius: 0; + background: none; + box-shadow: none; + animation: none; +} + +@media (max-width: 959px) { + .tb-greeting .tb-greet-spark { + --m: 34px; + } + + .tb-greeting.with-spark { + gap: 8px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.ts new file mode 100644 index 0000000000..25a2900df2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/welcome-home.component.ts @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState } from '@core/auth/auth.selectors'; + +@Component({ + selector: 'tb-welcome-home', + template: ` +
{{ today | date: 'EEEE d MMMM' }}
+

+ @if (spark()) { + + } + {{ (name ? 'home.greeting.' + daypart + '-name' : 'home.greeting.' + daypart) | translate: {name} }} +

+ `, + styleUrls: ['./welcome-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class WelcomeHomeComponent { + + spark = input(false); + + readonly today = new Date(); + + readonly daypart = this.today.getHours() < 12 ? 'morning' : this.today.getHours() < 18 ? 'afternoon' : 'evening'; + + readonly name = (() => { + const auth = getCurrentAuthState(inject(Store)); + return (auth?.userDetails?.firstName || auth?.authUser?.firstName || '').trim().split(/\s+/)[0] || null; + })(); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts new file mode 100644 index 0000000000..5ec95eaf53 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-cards.models.ts @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { HomeCardId, HomeCardsSettings } from '@shared/models/user-settings.models'; + +export interface HomeCardDefinition { + id: HomeCardId; + icon: string; + name: string; + link?: string; + height?: number; +} + +export const HOME_CARDS: Record = { + [HomeCardId.IOT_HUB]: {id: HomeCardId.IOT_HUB, icon: 'hub', name: 'home.cards.iot-hub', link: '/iot-hub'}, + [HomeCardId.ALARMS]: {id: HomeCardId.ALARMS, icon: 'warning', name: 'home.cards.alarms', link: '/alarms'}, + [HomeCardId.DASHBOARDS]: {id: HomeCardId.DASHBOARDS, icon: 'dashboard', name: 'home.cards.dashboards', link: '/dashboards'}, + [HomeCardId.DEVICES]: {id: HomeCardId.DEVICES, icon: 'memory', name: 'home.cards.devices', link: '/entities/devices'}, + [HomeCardId.ACTIVITY]: {id: HomeCardId.ACTIVITY, icon: 'show_chart', name: 'home.cards.activity'}, + [HomeCardId.GET_STARTED]: {id: HomeCardId.GET_STARTED, icon: 'rocket_launch', name: 'home.cards.get-started'}, + [HomeCardId.NOTIFICATIONS]: {id: HomeCardId.NOTIFICATIONS, icon: 'notifications', name: 'home.cards.notifications', + link: '/notification/inbox'}, + [HomeCardId.QUICK_LINKS]: {id: HomeCardId.QUICK_LINKS, icon: 'link', name: 'home.cards.quick-links'}, + [HomeCardId.USAGE]: {id: HomeCardId.USAGE, icon: 'data_usage', name: 'home.cards.usage', link: '/usage'}, + [HomeCardId.MOBILE_APP]: {id: HomeCardId.MOBILE_APP, icon: 'phone_iphone', name: 'home.cards.mobile-app'}, + [HomeCardId.PRODUCT_RELEASE]: {id: HomeCardId.PRODUCT_RELEASE, icon: 'new_releases', name: 'home.cards.product-release', height: 100}, + [HomeCardId.GET_STARTED_SYS_ADMIN]: {id: HomeCardId.GET_STARTED_SYS_ADMIN, icon: 'rocket_launch', name: 'home.cards.get-started'}, + [HomeCardId.SYSTEM_STATUS]: {id: HomeCardId.SYSTEM_STATUS, icon: 'dns', name: 'home.cards.system-status'}, + [HomeCardId.LICENSE]: {id: HomeCardId.LICENSE, icon: 'verified', name: 'home.cards.license', link: '/license'}, + [HomeCardId.INSTALL_ITEMS]: {id: HomeCardId.INSTALL_ITEMS, icon: 'domain', name: 'home.cards.install-items'} +}; + +export const isHomeCardShown = (settings: HomeCardsSettings, id: HomeCardId): boolean => settings?.[id] !== false; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts new file mode 100644 index 0000000000..6449ea8a75 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-chart.models.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export interface HomeChartTooltipRow { + color: string; + name: string; + value: string; +} + +const escapeHtml = (text: string): string => + text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +export const homeChartTooltipHtml = (header: string, rows: HomeChartTooltipRow[]): string => { + const items = rows.map(row => '' + + `' + + `${escapeHtml(row.name)}${escapeHtml(row.value)}`).join(''); + return '
${escapeHtml(header)}${items}
`; +}; + +export const homeChartTooltipOptions = { + trigger: 'axis' as const, + confine: true, + axisPointer: {type: 'line' as const, lineStyle: {color: 'rgba(0, 0, 0, 0.38)', type: 'dashed' as const, width: 1}}, + position: (point: number[], _params: unknown, _dom: unknown, _rect: unknown, size: {contentSize: number[]; viewSize: number[]}) => + [point[0] > size.viewSize[0] * 0.6 ? point[0] - 10 - size.contentSize[0] : point[0] + 10, 0], + padding: [6, 8], + backgroundColor: 'rgba(0, 0, 0, 0.87)', + borderWidth: 0, + extraCssText: 'border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16); min-width: 96px; box-sizing: border-box;' +}; + +export const homeChartHoverSymbol = (color: string) => ({ + symbol: 'circle', + symbolSize: 8, + itemStyle: {color, borderColor: '#fff', borderWidth: 2}, + emphasis: {scale: false} +}); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts new file mode 100644 index 0000000000..13c6882eb7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { DestroyRef, inject, Injectable, NgZone } from '@angular/core'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityType } from '@shared/models/entity-type.models'; +import { KeyFilter } from '@shared/models/query/query.models'; + +interface SharedCount { + subscriber: TelemetrySubscriber; + listeners: Set<(count: number) => void>; + last?: number; +} + +@Injectable({ + providedIn: 'root' +}) +export class HomeCountService { + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private counts = new Map(); + + watchEntityCount(entityType: EntityType, onCount: (count: number) => void, destroyRef: DestroyRef, keyFilters?: KeyFilter[]): () => void { + const key = JSON.stringify([entityType, keyFilters ?? null]); + let shared = this.counts.get(key); + if (!shared) { + const cmd = new EntityCountCmd(); + cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType}, keyFilters}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + const created: SharedCount = {subscriber, listeners: new Set()}; + subscriber.entityCount$.subscribe(update => { + created.last = update.count ?? 0; + created.listeners.forEach(listener => listener(created.last)); + }); + subscriber.subscribe(); + this.counts.set(key, created); + shared = created; + } else if (shared.last !== undefined) { + onCount(shared.last); + } + shared.listeners.add(onCount); + let released = false; + const release = () => { + if (released) { + return; + } + released = true; + shared.listeners.delete(onCount); + if (!shared.listeners.size) { + shared.subscriber.unsubscribe(); + this.counts.delete(key); + } + }; + destroyRef.onDestroy(release); + return release; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts new file mode 100644 index 0000000000..7e6ee899ed --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; +import { MINUTE } from '@shared/models/time/time.models'; +import { NotificationMessage } from '@core/notification/notification.models'; + +export const HOME_LIST_PREVIEW = 5; +export const HOME_LIST_SLACK = 2; +export const HOME_LIST_LIMIT = 10; + +export const homeListPageSize = (expanded: boolean): number => expanded ? HOME_LIST_LIMIT : HOME_LIST_PREVIEW + HOME_LIST_SLACK; + +export const homeListFew = (total: number): boolean => total <= HOME_LIST_PREVIEW + HOME_LIST_SLACK; + +export const homeListShown = (total: number, expanded: boolean): number => { + if (homeListFew(total)) { + return total; + } + return expanded ? Math.min(total, HOME_LIST_LIMIT) : HOME_LIST_PREVIEW; +}; + +const agoText = (translate: TranslateService, ms: number, prefix: string): string => { + const min = ms / MINUTE; + if (min < 1) { + return translate.instant(`${prefix}.now`); + } + if (min < 60) { + return translate.instant(`${prefix}.min`, {count: Math.round(min)}); + } + if (min < 24 * 60) { + return translate.instant(`${prefix}.hour`, {count: Math.floor(min / 60)}); + } + if (min < 7 * 24 * 60) { + return translate.instant(`${prefix}.day`, {count: Math.floor(min / (24 * 60))}); + } + return translate.instant(`${prefix}.week`, {count: Math.floor(min / (7 * 24 * 60))}); +}; + +export const homeAgo = (translate: TranslateService, ms: number): string => agoText(translate, ms, 'home.ago'); + +export const homeElapsed = (translate: TranslateService, ms: number): string => agoText(translate, ms, 'home.elapsed'); + +const HOME_TOAST_MS = 4000; +const HOME_UNDO_MS = 6000; + +export const homeToast = (message: string, undo?: {label: string; action: () => void}): NotificationMessage => ({ + message, + type: 'info', + duration: undo ? HOME_UNDO_MS : HOME_TOAST_MS, + horizontalPosition: 'right', + verticalPosition: 'bottom', + panelClass: 'tb-home-toast', + ...(undo ? {actionLabel: undo.label, onAction: undo.action} : {}) +}); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page-routing.module.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-page-routing.module.ts new file mode 100644 index 0000000000..a7f7fbb8df --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page-routing.module.ts @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { inject, NgModule } from '@angular/core'; +import { ActivatedRouteSnapshot, ResolveFn, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; + +import { HomePageComponent } from './home-page.component'; +import { Authority } from '@shared/models/authority.enum'; +import { mergeMap, Observable, of } from 'rxjs'; +import { HomeDashboard } from '@shared/models/dashboard.models'; +import { DashboardService } from '@core/http/dashboard.service'; +import { catchError, first, map } from 'rxjs/operators'; +import { MenuId } from '@core/services/menu.models'; +import { MenuService } from '@core/services/menu.service'; + +const resolveMenuHomeDashboard = (menuService: MenuService, + dashboardService: DashboardService): Observable => + menuService.menuSections().pipe(first()).pipe( + mergeMap((sections) => { + const homeSection = sections.find(s => s.id === MenuId.home); + if (homeSection?.homeDashboardId) { + return dashboardService.getDashboard(homeSection.homeDashboardId, {ignoreErrors: true}).pipe( + map((dashboard) => ({ + ...dashboard, + hideDashboardToolbar: homeSection.homeHideDashboardToolbar + })), + catchError(() => of(null)) + ); + } + return of(null); + }) + ); + +const resolveHomeDashboard = (menuService: MenuService, + dashboardService: DashboardService): Observable => + dashboardService.getHomeDashboard().pipe( + mergeMap((dashboard) => { + if (!dashboard) { + return resolveMenuHomeDashboard(menuService, dashboardService); + } + return of(dashboard); + }), + catchError(() => resolveMenuHomeDashboard(menuService, dashboardService)) + ); + +export const homeDashboardResolver: ResolveFn = ( + _route: ActivatedRouteSnapshot, + _state: RouterStateSnapshot, + menuService = inject(MenuService), + dashboardService = inject(DashboardService) +): Observable => resolveHomeDashboard(menuService, dashboardService); + +const routes: Routes = [ + { + path: 'home', + component: HomePageComponent, + data: { + auth: [Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER], + title: 'home.home', + breadcrumb: { + menuId: MenuId.home + } + }, + resolve: { + homeDashboard: homeDashboardResolver + } + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class HomePageRoutingModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html new file mode 100644 index 0000000000..fa167756ab --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html @@ -0,0 +1,25 @@ + +@if (homeDashboard) { + +} @else if (authenticated()) { + @if (aiSky) { + + } + @switch (authority) { + @case (Authority.SYS_ADMIN) { + + } + @case (Authority.TENANT_ADMIN) { + + } + @case (Authority.CUSTOMER_USER) { + + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss new file mode 100644 index 0000000000..07b4f7061a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +tb-home-page.tb-home-dashboard { + display: block; + width: 100%; + height: 100%; +} + +tb-home-page:not(.tb-home-dashboard) { + --tb-home-page: #f4f6f7; + --tb-home-ai-glow: oklch(0.80 0.11 182); + --tb-home-card-shadow: 0 1px 1px rgba(20, 52, 58, 0.06), 0 2px 6px -1px rgba(20, 52, 58, 0.08); + position: relative; + isolation: isolate; + display: block; + flex: none; + min-height: 100%; + box-sizing: border-box; + container: tb-home / inline-size; + background-color: var(--tb-home-page); + background-image: + radial-gradient(1300px 560px at 16% -120px, color-mix(in oklab, var(--tb-home-ai-glow) 34%, var(--tb-home-page)) 0%, + color-mix(in oklab, var(--tb-home-ai-glow) 12%, var(--tb-home-page)) 42%, var(--tb-home-page) 78%), + linear-gradient(180deg, #eaedef 0px, var(--tb-home-page) 360px); + background-repeat: no-repeat; +} + +tb-home-page .tb-home-sky { + position: absolute; + top: 0; + left: 0; + right: 0; + z-index: -1; + height: 600px; + overflow: hidden; + pointer-events: none; + background: var(--ai-field-wash); + -webkit-mask-image: linear-gradient(180deg, #000 0, #000 200px, transparent 100%); + mask-image: linear-gradient(180deg, #000 0, #000 200px, transparent 100%); + animation: tb-home-sky-in 1.2s cubic-bezier(.4, 0, .2, 1); + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes tb-home-sky-in { + from { + opacity: 0; + } +} + +@supports (color: oklch(from red l c h)) { + tb-home-page.tenant-brand:not(.tb-home-dashboard) { + --tb-home-tenant-glow: oklch(from var(--tb-primary-500) 0.80 min(c, 0.11) h); + background-image: + radial-gradient(820px 520px at 6% -120px, color-mix(in oklab, var(--tb-home-tenant-glow) 34%, transparent) 0%, + color-mix(in oklab, var(--tb-home-tenant-glow) 12%, transparent) 42%, transparent 78%), + radial-gradient(900px 520px at 80% -140px, color-mix(in oklab, var(--tb-home-ai-glow) 34%, transparent) 0%, + color-mix(in oklab, var(--tb-home-ai-glow) 12%, transparent) 42%, transparent 78%), + linear-gradient(180deg, #eaedef 0px, var(--tb-home-page) 360px); + } + + tb-home-page.tenant-brand:not(.tb-home-dashboard) .tb-home-sky { + --tb-home-sky-field: oklch(from var(--tb-primary-500) 0.86 min(c, 0.08) h); + --tb-home-sky-soft: oklch(from var(--tb-primary-500) 0.89 min(c, 0.05) h); + background: + radial-gradient(46% 80% at 41% 24%, color-mix(in oklab, var(--ai-light-lilac) calc(var(--ai-w-lilac) * .87), transparent), transparent 72%), + radial-gradient(70% 88% at 14% 2%, color-mix(in oklab, var(--tb-home-sky-field) calc(var(--ai-w-teal) * .87), transparent), transparent 70%), + radial-gradient(72% 82% at 66% 0%, color-mix(in oklab, var(--ai-light-teal) calc(var(--ai-w-teal) * .87), transparent), transparent 70%), + radial-gradient(44% 56% at 2% 96%, color-mix(in oklab, var(--tb-home-sky-soft) calc(var(--ai-w-mint) * .87), transparent), transparent 70%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .87), transparent), transparent 70%), + radial-gradient(50% 70% at 100% 52%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .87), transparent), transparent 70%), + var(--ai-light-paper); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts new file mode 100644 index 0000000000..4db28b4d77 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, inject, ViewEncapsulation } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser, selectIsAuthenticated } from '@core/auth/auth.selectors'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { Authority } from '@shared/models/authority.enum'; +import { HomeDashboard } from '@shared/models/dashboard.models'; +import { TourService } from '@core/services/tour.service'; + +const DEFAULT_PRIMARY = '#00695c'; + +@Component({ + selector: 'tb-home-page', + templateUrl: './home-page.component.html', + styleUrls: ['./home-page.component.scss', './components/home-toast.scss', './components/home-menu.scss'], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false, + host: { + '[class.tb-home-dashboard]': '!!homeDashboard', + '[class.tenant-brand]': '!homeDashboard && tenantBrand' + } +}) +export class HomePageComponent { + + readonly Authority = Authority; + + readonly authenticated = toSignal(inject(Store).select(selectIsAuthenticated), {initialValue: true}); + + readonly homeDashboard: HomeDashboard = inject(ActivatedRoute).snapshot.data.homeDashboard; + + readonly authority = getCurrentAuthUser(inject(Store))?.authority; + + readonly aiSky = !this.homeDashboard && inject(TourService).aiAvailable(); + + readonly tenantBrand = getComputedStyle(document.body).getPropertyValue('--tb-primary-500') + .trim().toLowerCase() !== DEFAULT_PRIMARY; +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts new file mode 100644 index 0000000000..a70a6ebf88 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { HomePageRoutingModule } from './home-page-routing.module'; +import { HomePageComponent } from './home-page.component'; +import { SharedModule } from '@app/shared/shared.module'; +import { HomeComponentsModule } from '@home/components/home-components.module'; + +import { SysAdminHomeComponent } from '@home/pages/home-page/pages/sys-admin-home.component'; +import { TenantAdminHomeComponent } from '@home/pages/home-page/pages/tenant-admin-home.component'; +import { CustomerUserHomeComponent } from '@home/pages/home-page/pages/customer-user-home.component'; +import { HomeCardComponent } from '@home/pages/home-page/components/home-card.component'; +import { WelcomeHomeComponent } from '@home/pages/home-page/components/welcome-home.component'; +import { StatusLineHomeComponent } from '@home/pages/home-page/components/status-line-home.component'; +import { AiAssistantHomeComponent } from '@home/pages/home-page/components/ai-assistant-home.component'; +import { WaitingAIChatsHomeComponent } from '@home/pages/home-page/components/waiting-ai-chats-home.component'; +import { IoTHubHomeComponent } from '@home/pages/home-page/components/iot-hub-home.component'; +import { AlarmsHomeComponent } from '@home/pages/home-page/components/alarms-home.component'; +import { DashboardsHomeComponent } from '@home/pages/home-page/components/dashboards-home.component'; +import { DevicesHomeComponent } from '@home/pages/home-page/components/devices-home.component'; +import { DevicesActivityHomeComponent } from '@home/pages/home-page/components/devices-activity-home.component'; +import { GetStartedHomeComponent } from '@home/pages/home-page/components/get-started-home.component'; +import { NotificationsHomeComponent } from '@home/pages/home-page/components/notifications-home.component'; +import { QuickLinksHomeComponent } from '@home/pages/home-page/components/quick-links-home.component'; +import { ApiUsageHomeComponent } from '@home/pages/home-page/components/api-usage-home.component'; +import { MobileAppHomeComponent } from '@home/pages/home-page/components/mobile-app-home.component'; +import { HomeCardsFooterComponent } from '@home/pages/home-page/components/home-cards-footer.component'; +import { CustomizeHomeDialogComponent } from '@home/pages/home-page/components/customize-home-dialog.component'; +import { QuickLinkDialogComponent } from '@home/pages/home-page/components/quick-link-dialog.component'; +import { HomeHscrollComponent } from '@home/pages/home-page/components/home-hscroll.component'; +import { HomeToggleComponent } from '@home/pages/home-page/components/home-toggle.component'; +import { HomeListFooterComponent } from '@home/pages/home-page/components/home-list-footer.component'; +import { AiStartHomeComponent } from '@home/pages/home-page/components/ai-start-home.component'; +import { ProductReleaseHomeComponent } from '@home/pages/home-page/components/product-release-home.component'; +import { GetStartedSysAdminHomeComponent } from '@home/pages/home-page/components/get-started-sys-admin-home.component'; +import { SystemStatusHomeComponent } from '@home/pages/home-page/components/system-status-home.component'; +import { LicenseHomeComponent } from '@home/pages/home-page/components/license-home.component'; +import { InstallItemsHomeComponent } from '@home/pages/home-page/components/install-items-home.component'; +import { AiComposerModule } from '@home/components/ai/ai-composer.module'; + +@NgModule({ + declarations: + [ + HomePageComponent, + SysAdminHomeComponent, + TenantAdminHomeComponent, + CustomerUserHomeComponent, + HomeCardComponent, + WelcomeHomeComponent, + StatusLineHomeComponent, + AiAssistantHomeComponent, + WaitingAIChatsHomeComponent, + IoTHubHomeComponent, + AlarmsHomeComponent, + DashboardsHomeComponent, + DevicesHomeComponent, + DevicesActivityHomeComponent, + GetStartedHomeComponent, + NotificationsHomeComponent, + QuickLinksHomeComponent, + ApiUsageHomeComponent, + MobileAppHomeComponent, + HomeCardsFooterComponent, + CustomizeHomeDialogComponent, + QuickLinkDialogComponent, + HomeHscrollComponent, + HomeToggleComponent, + HomeListFooterComponent, + AiStartHomeComponent, + ProductReleaseHomeComponent, + GetStartedSysAdminHomeComponent, + SystemStatusHomeComponent, + LicenseHomeComponent, + InstallItemsHomeComponent + ], + imports: [ + CommonModule, + SharedModule, + HomeComponentsModule, + AiComposerModule, + HomePageRoutingModule + ] +}) +export class HomePageModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-permissions.service.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-permissions.service.ts new file mode 100644 index 0000000000..414e3e6628 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-permissions.service.ts @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType } from '@shared/models/entity-type.models'; +import { Operation, Resource, resourceByEntityType } from '@shared/models/security.models'; +import { alarmRuleEntityTypeList } from '@shared/models/alarm-rule.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { HomeCardId } from '@shared/models/user-settings.models'; + +const ENTITY_LIST_PATHS: Partial> = { + [EntityType.DEVICE]: '/entities/devices', + [EntityType.ASSET]: '/entities/assets', + [EntityType.CUSTOMER]: '/customers', + [EntityType.DASHBOARD]: '/dashboards' +}; + +@Injectable({ + providedIn: 'root' +}) +export class HomePermissionsService { + + private userPermissions = inject(UserPermissionsService); + private store = inject(Store); + + get tenantAdmin(): boolean { + return getCurrentAuthUser(this.store)?.authority === Authority.TENANT_ADMIN; + } + + canReadEntities(entityType: EntityType): boolean { + return this.userPermissions.hasReadGenericPermission(resourceByEntityType.get(entityType)) || + this.userPermissions.hasSharedReadGroupsPermission(entityType); + } + + canReadAllEntities(entityType: EntityType): boolean { + return this.userPermissions.hasReadGenericPermission(resourceByEntityType.get(entityType)); + } + + canCreateEntities(entityType: EntityType): boolean { + return this.userPermissions.hasGenericPermission(resourceByEntityType.get(entityType), Operation.CREATE); + } + + entitiesLink(entityType: EntityType): string | null { + const base = ENTITY_LIST_PATHS[entityType]; + if (!base) { + return null; + } + if (this.canReadAllEntities(entityType)) { + return `${base}/all`; + } + return this.userPermissions.hasSharedReadGroupsPermission(entityType) ? `${base}/shared` : null; + } + + entityDetailsLink(entityType: EntityType, id: string): string | null { + if (!this.canReadAllEntities(entityType)) { + return null; + } + return getEntityDetailsPageURL(id, entityType) || null; + } + + canReadAlarms(): boolean { + return this.userPermissions.hasReadGenericPermission(Resource.ALARM); + } + + canWriteAlarms(): boolean { + return this.userPermissions.hasGenericPermission(Resource.ALARM, Operation.WRITE); + } + + canReadAlarmRules(): boolean { + return this.tenantAdmin && alarmRuleEntityTypeList.some(entityType => + this.userPermissions.hasGenericPermissionByEntityGroupType(Operation.READ_CALCULATED_FIELD, entityType)); + } + + canAddAlarmRules(): boolean { + return this.tenantAdmin && alarmRuleEntityTypeList.some(entityType => + this.userPermissions.hasGenericPermissionByEntityGroupType(Operation.WRITE_CALCULATED_FIELD, entityType)); + } + + canUseIotHub(): boolean { + return this.tenantAdmin && this.userPermissions.hasGenericPermission(Resource.ALL, Operation.ALL); + } + + canReadApiUsage(): boolean { + return this.tenantAdmin && this.userPermissions.hasReadGenericPermission(Resource.API_USAGE_STATE) && + this.userPermissions.hasGenericPermission(Resource.API_USAGE_STATE, Operation.READ_TELEMETRY); + } + + canReadUsageInfo(): boolean { + return this.tenantAdmin && this.userPermissions.hasGenericPermission(Resource.ALL, Operation.READ); + } + + canReadMobileAppSettings(): boolean { + return this.userPermissions.hasReadGenericPermission(Resource.MOBILE_APP_SETTINGS); + } + + canGetStarted(): boolean { + return this.tenantAdmin && this.canAddAlarmRules() && + [EntityType.DEVICE, EntityType.DASHBOARD, EntityType.CUSTOMER].every(entityType => + this.canReadAllEntities(entityType) && this.canCreateEntities(entityType)); + } + + cardAvailable(id: HomeCardId): boolean { + switch (id) { + case HomeCardId.GET_STARTED: + return this.canGetStarted(); + case HomeCardId.IOT_HUB: + return this.canUseIotHub(); + case HomeCardId.ALARMS: + return this.canReadAlarms(); + case HomeCardId.DASHBOARDS: + return this.canReadEntities(EntityType.DASHBOARD); + case HomeCardId.DEVICES: + return this.canReadEntities(EntityType.DEVICE); + case HomeCardId.ACTIVITY: + return this.canReadApiUsage(); + case HomeCardId.USAGE: + return this.canReadUsageInfo(); + case HomeCardId.MOBILE_APP: + return this.canReadMobileAppSettings(); + default: + return true; + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/pages/customer-user-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/pages/customer-user-home.component.ts new file mode 100644 index 0000000000..e3e4b5b87c --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/pages/customer-user-home.component.ts @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectHomeCards } from '@core/auth/auth.selectors'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { isHomeCardShown } from '@home/pages/home-page/home-cards.models'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; + +const MAIN_CARDS = [HomeCardId.ALARMS, HomeCardId.DASHBOARDS, HomeCardId.DEVICES]; +const SIDE_CARDS = [HomeCardId.NOTIFICATIONS, HomeCardId.QUICK_LINKS]; + +@Component({ + selector: 'tb-customer-user-home', + template: ` + + @switch (id) { + @case (HomeCardId.ALARMS) { + + } + @case (HomeCardId.DASHBOARDS) { + + } + @case (HomeCardId.DEVICES) { + + } + @case (HomeCardId.NOTIFICATIONS) { + + } + @case (HomeCardId.QUICK_LINKS) { + + } + } + +
+
+ + +
+
+
+ @for (id of mainCards(); track id) { + + } +
+
+ @for (id of sideCards(); track id) { + + } +
+
+ +
+ `, + styleUrls: ['./tenant-admin-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class CustomerUserHomeComponent { + + readonly HomeCardId = HomeCardId; + + private readonly permissions = inject(HomePermissionsService); + + private readonly mainCardIds = MAIN_CARDS.filter(id => this.permissions.cardAvailable(id)); + + private readonly sideCardIds = SIDE_CARDS.filter(id => this.permissions.cardAvailable(id)); + + readonly cards = [...this.mainCardIds, ...this.sideCardIds]; + + private settings = toSignal(inject(Store).select(selectHomeCards), {initialValue: {}}); + + private readonly shownMainCards = computed(() => this.mainCardIds.filter(id => isHomeCardShown(this.settings(), id))); + + private readonly shownSideCards = computed(() => this.sideCardIds.filter(id => isHomeCardShown(this.settings(), id))); + + readonly mainCards = computed(() => this.shownMainCards().length ? this.shownMainCards() : this.shownSideCards()); + + readonly sideCards = computed(() => this.shownMainCards().length ? this.shownSideCards() : []); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/pages/sys-admin-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/pages/sys-admin-home.component.ts new file mode 100644 index 0000000000..2a968387d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/pages/sys-admin-home.component.ts @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectHomeCards, selectMobileQrEnabled } from '@core/auth/auth.selectors'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { isHomeCardShown } from '@home/pages/home-page/home-cards.models'; +import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; + +const MAIN_CARDS = [HomeCardId.GET_STARTED_SYS_ADMIN, HomeCardId.SYSTEM_STATUS, HomeCardId.LICENSE, HomeCardId.ACTIVITY]; +const SIDE_CARDS = [HomeCardId.NOTIFICATIONS, HomeCardId.INSTALL_ITEMS, HomeCardId.QUICK_LINKS, HomeCardId.MOBILE_APP]; + +@Component({ + selector: 'tb-sys-admin-home', + template: ` + + @switch (id) { + @case (HomeCardId.GET_STARTED_SYS_ADMIN) { + + } + @case (HomeCardId.SYSTEM_STATUS) { + + } + @case (HomeCardId.LICENSE) { + + } + @case (HomeCardId.ACTIVITY) { + + } + @case (HomeCardId.NOTIFICATIONS) { + + } + @case (HomeCardId.INSTALL_ITEMS) { + + } + @case (HomeCardId.QUICK_LINKS) { + + } + @case (HomeCardId.MOBILE_APP) { + + } + } + +
+
+ + +
+
+
+ + @for (id of mainCards(); track id) { + + } +
+
+ @for (id of sideCards(); track id) { + + } +
+
+ +
+ `, + styleUrls: ['./tenant-admin-home.component.scss'], + providers: [SysAdminHomeService], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class SysAdminHomeComponent { + + readonly HomeCardId = HomeCardId; + + private readonly store = inject(Store); + + private readonly settings = toSignal(this.store.select(selectHomeCards), {initialValue: {}}); + + private readonly mobileQrEnabled = toSignal(this.store.select(selectMobileQrEnabled), {initialValue: false}); + + readonly getStartedShown = computed(() => isHomeCardShown(this.settings(), HomeCardId.GET_STARTED_SYS_ADMIN)); + + readonly cards = computed(() => [...MAIN_CARDS, ...SIDE_CARDS].filter(id => this.available(id))); + + readonly mainCards = computed(() => MAIN_CARDS.filter(id => this.shown(id))); + + readonly sideCards = computed(() => SIDE_CARDS.filter(id => this.shown(id))); + + constructor() { + inject(SysAdminHomeService).featuresInfo$.subscribe(); + } + + private available(id: HomeCardId): boolean { + return id !== HomeCardId.MOBILE_APP || this.mobileQrEnabled(); + } + + private shown(id: HomeCardId): boolean { + return this.available(id) && isHomeCardShown(this.settings(), id); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.html new file mode 100644 index 0000000000..cc65b28885 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.html @@ -0,0 +1,66 @@ + + + @switch (id) { + @case (HomeCardId.IOT_HUB) { + + } + @case (HomeCardId.ALARMS) { + + } + @case (HomeCardId.DASHBOARDS) { + + } + @case (HomeCardId.DEVICES) { + + } + @case (HomeCardId.ACTIVITY) { + + } + @case (HomeCardId.GET_STARTED) { + + } + @case (HomeCardId.NOTIFICATIONS) { + + } + @case (HomeCardId.QUICK_LINKS) { + + } + @case (HomeCardId.USAGE) { + + } + @case (HomeCardId.MOBILE_APP) { + + } + } + +
+
+ + +
+
+ @if (aiAvailable) { +
+ + + +
+ } +
+ @for (id of mainCards(); track id) { + + } +
+
+ @for (id of sideCards(); track id) { + + } +
+
+ +
diff --git a/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.scss new file mode 100644 index 0000000000..8713f6fc7c --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.scss @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; +} + +.tb-home { + display: flex; + flex-direction: column; + gap: 16px; + box-sizing: border-box; + max-width: 1200px; + margin: 0 auto; + padding: 16px 24px 48px; +} + +.tb-home-head { + padding: 28px 0 12px; +} + +.tb-home-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 16px; + align-items: start; +} + +.tb-col { + display: flex; + flex-direction: column; + gap: 16px; + min-width: 0; +} + +.tb-grid-hero { + --tb-home-compose-width: 760px; + min-width: 0; +} + +@media (min-width: 960px) { + @container tb-home (min-width: 808px) { + .tb-home-grid { + grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); + } + + .tb-home-grid.with-hero { + > .tb-grid-hero { + --tb-home-compose-width: min(760px, calc((min(100cqw, 1200px) - 64px) * 2 / 3)); + grid-column: 1 / -1; + grid-row: 1; + max-width: 760px; + } + + > .tb-col-main { + grid-column: 1; + grid-row: 2; + } + + > .tb-col-side { + grid-column: 2; + grid-row: 2; + } + } + } + + @container tb-home (min-width: 1024px) { + .tb-home-grid.with-hero { + grid-template-rows: auto 1fr; + + > .tb-grid-hero { + --tb-home-compose-width: min(760px, calc(100% - 48px)); + grid-column: 1; + max-width: none; + } + + > .tb-col-side { + grid-row: 1 / span 2; + } + } + } +} + +@media (min-width: 1920px) { + .tb-home { + max-width: 1440px; + } + + @container tb-home (min-width: 808px) { + .tb-home-grid { + grid-template-columns: minmax(0, 1fr) 400px; + } + } +} + +@media (max-width: 599px) { + .tb-home { + padding: 8px 12px 32px; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.ts new file mode 100644 index 0000000000..8d75816242 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/pages/tenant-admin-home.component.ts @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectHomeCards, selectMobileQrEnabled } from '@core/auth/auth.selectors'; +import { TourService } from '@core/services/tour.service'; +import { HomeCardId } from '@shared/models/user-settings.models'; +import { isHomeCardShown } from '@home/pages/home-page/home-cards.models'; +import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; + +const MAIN_CARDS = [HomeCardId.IOT_HUB, HomeCardId.ALARMS, HomeCardId.DASHBOARDS, HomeCardId.DEVICES, HomeCardId.ACTIVITY]; +const SIDE_CARDS = [HomeCardId.GET_STARTED, HomeCardId.NOTIFICATIONS, HomeCardId.QUICK_LINKS, HomeCardId.USAGE, HomeCardId.MOBILE_APP]; + +@Component({ + selector: 'tb-tenant-admin-home', + templateUrl: './tenant-admin-home.component.html', + styleUrls: ['./tenant-admin-home.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class TenantAdminHomeComponent { + + readonly HomeCardId = HomeCardId; + + private readonly store = inject(Store); + + private readonly permissions = inject(HomePermissionsService); + + private readonly mobileQrEnabled = toSignal(this.store.select(selectMobileQrEnabled), {initialValue: false}); + + private readonly mainCardIds = MAIN_CARDS.filter(id => this.permissions.cardAvailable(id)); + + private readonly sideCardIds = computed(() => SIDE_CARDS.filter(id => + this.permissions.cardAvailable(id) && (id !== HomeCardId.MOBILE_APP || this.mobileQrEnabled()))); + + readonly cards = computed(() => [...this.mainCardIds, ...this.sideCardIds()]); + + readonly aiAvailable = inject(TourService).aiAvailable(); + + private settings = toSignal(this.store.select(selectHomeCards), {initialValue: {}}); + + private readonly shownMainCards = computed(() => this.mainCardIds.filter(id => isHomeCardShown(this.settings(), id))); + + private readonly shownSideCards = computed(() => this.sideCardIds().filter(id => isHomeCardShown(this.settings(), id))); + + readonly mainCards = computed(() => this.shownMainCards().length ? this.shownMainCards() : this.shownSideCards()); + + readonly sideCards = computed(() => this.shownMainCards().length ? this.shownSideCards() : []); +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts new file mode 100644 index 0000000000..dd1a57a9f3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Params } from '@angular/router'; +import { Authority } from '@shared/models/authority.enum'; +import { DocumentationLink, QUICK_WEB_LINK_PREFIX, QuickLinks } from '@shared/models/user-settings.models'; +import { MenuSection } from '@core/services/menu.models'; +import { guid } from '@core/utils'; + +export const QUICK_LINKS_MAX = 12; + +export const QUICK_LINK_ICONS = ['link', 'public', 'menu_book', 'description', 'school', 'help_outline', 'support_agent', + 'insert_chart', 'dashboard', 'map', 'code', 'build', 'cloud', 'storage', 'folder', 'chat']; + +export interface QuickLinkPage { + id: string; + name: string; + icon: string; + path: string; + queryParams?: Params; + crumb: string; +} + +export interface QuickLinkView { + id: string; + name: string; + icon: string; + page?: QuickLinkPage; + web?: DocumentationLink; +} + +export type QuickLinkDialogResult = {page: QuickLinkPage} | {web: DocumentationLink}; + +export const isQuickWebLinkId = (id: string): boolean => id.startsWith(QUICK_WEB_LINK_PREFIX); + +export const quickWebLinkId = (): string => QUICK_WEB_LINK_PREFIX + guid(); + +export const defaultQuickLinks = (authority: Authority, docsUrl: string, translate: (key: string) => string): QuickLinks => { + const web = (id: string, name: string, icon: string, link: string) => ({[QUICK_WEB_LINK_PREFIX + id]: {name, icon, link}}); + switch (authority) { + case Authority.SYS_ADMIN: + return { + links: ['getting-started', 'tenant-profiles', 'api', 'widgets-library'].map(id => QUICK_WEB_LINK_PREFIX + id), + webLinks: { + ...web('getting-started', translate('home.quick-links.getting-started'), 'rocket_launch', docsUrl + 'getting-started/'), + ...web('tenant-profiles', translate('home.quick-links.tenant-profiles'), 'account_box', docsUrl + 'user-guide/tenant-profiles/'), + ...web('api', translate('home.quick-links.api'), 'api', docsUrl + 'apis-and-sdks/'), + ...web('widgets-library', translate('home.quick-links.widgets-library'), 'widgets', docsUrl + 'reference/widgets/widget-library/') + } + }; + case Authority.CUSTOMER_USER: + return { + links: ['assets', 'entity_views', 'notification_inbox', QUICK_WEB_LINK_PREFIX + 'user-guide'], + webLinks: web('user-guide', translate('home.quick-links.user-guide'), 'menu_book', docsUrl + 'user-guide/') + }; + default: + return { + links: ['assets', 'device_profiles', 'rule_chains', 'gateways', 'customers', QUICK_WEB_LINK_PREFIX + 'docs'], + webLinks: web('docs', translate('home.quick-links.documentation'), 'menu_book', docsUrl) + }; + } +}; + +export const quickLinkPages = (sections: MenuSection[], translateName: (section: MenuSection) => string, + result: QuickLinkPage[] = [], parents: string[] = []): QuickLinkPage[] => { + for (const section of sections) { + const name = translateName(section); + if (section.type === 'link' && section.id !== 'home') { + result.push({ + id: section.id, + name, + icon: section.outlinedIcon || section.icon, + path: section.path, + queryParams: section.queryParams, + crumb: parents.join(' • ') + }); + } + if (section.pages?.length) { + quickLinkPages(section.pages, translateName, result, [...parents, name]); + } + } + return result; +}; + +export const quickLinkIconFromUrl = (url: URL): string => { + const text = (url.hostname + url.pathname).toLowerCase(); + if (/(^|\.)docs?\.|\/docs?(\/|$)|wiki|confluence|readme|manual/.test(text)) { + return 'menu_book'; + } + if (/grafana|kibana|metabase|superset|powerbi|tableau/.test(text)) { + return 'insert_chart'; + } + if (/github|gitlab|bitbucket/.test(text)) { + return 'code'; + } + if (/support|helpdesk|zendesk|freshdesk|servicenow|jira/.test(text)) { + return 'support_agent'; + } + return 'link'; +}; + +export const quickLinkNameFromUrl = (url: URL): string => { + const segment = url.pathname.split('/').filter(Boolean).pop(); + if (segment) { + let text: string; + try { + text = decodeURIComponent(segment); + } catch { + text = segment; + } + text = text.replace(/[-_]+/g, ' ').replace(/\.\w+$/, '').trim(); + if (text) { + return text.charAt(0).toUpperCase() + text.slice(1); + } + } + return url.hostname.replace(/^www\./, ''); +}; + +export const parseQuickWebLink = (raw: string): {url?: URL; error?: 'scheme' | 'invalid'} => { + const value = raw.trim(); + if (!value) { + return {}; + } + const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(value) ? value : 'https://' + value; + let url: URL; + try { + url = new URL(withScheme); + } catch { + return {error: 'invalid'}; + } + if (!/^https?:$/.test(url.protocol)) { + return {error: 'scheme'}; + } + if (!/\./.test(url.hostname) && url.hostname !== 'localhost') { + return {error: 'invalid'}; + } + return {url}; +}; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts b/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts new file mode 100644 index 0000000000..26a328d66b --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/sys-admin-home.service.ts @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable, signal } from '@angular/core'; +import { Observable, of } from 'rxjs'; +import { catchError, shareReplay } from 'rxjs/operators'; +import { AdminService } from '@core/http/admin.service'; +import { FeaturesInfo, UpdateMessage } from '@shared/models/settings.models'; + +let hiddenRelease: string | null = null; + +@Injectable() +export class SysAdminHomeService { + + private adminService = inject(AdminService); + + readonly featuresInfo$: Observable = this.adminService.getFeaturesInfo({ignoreErrors: true, ignoreLoading: true}).pipe( + catchError(() => of(null)), + shareReplay(1) + ); + + readonly update$: Observable = this.adminService.checkUpdates({ignoreErrors: true, ignoreLoading: true}).pipe( + catchError(() => of(null)), + shareReplay(1) + ); + + readonly hiddenRelease = signal(hiddenRelease); + + setHiddenRelease(version: string | null): void { + hiddenRelease = version; + this.hiddenRelease.set(version); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts index a6effb867d..1a2a0182bf 100644 --- a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts +++ b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts @@ -4,7 +4,7 @@ import { NgModule } from '@angular/core'; import { AdminModule } from './admin/admin.module'; -import { HomeLinksModule } from './home-links/home-links.module'; +import { HomePageModule } from './home-page/home-page.module'; import { ProfileModule } from './profile/profile.module'; import { SecurityModule } from '@home/pages/security/security.module'; import { TenantModule } from '@modules/home/pages/tenant/tenant.module'; @@ -29,7 +29,6 @@ import { DeviceProfileModule } from './device-profile/device-profile.module'; import { ApiUsageModule } from '@home/pages/api-usage/api-usage.module'; import { EdgeModule } from '@home/pages/edge/edge.module'; import { OtaUpdateModule } from '@home/pages/ota-update/ota-update.module'; -import { SolutionCreatorModule } from '@home/pages/ai-solution-creator/solution-creator.module'; import { VcModule } from '@home/pages/vc/vc.module'; import { TaskManagerModule } from '@home/pages/task-manager/task-manager.module'; import { AssetProfileModule } from '@home/pages/asset-profile/asset-profile.module'; @@ -52,11 +51,12 @@ import { TrendzAnalyticsModule } from '@home/pages/trendz-analytics/trendz-analy import { TrendzSettingsModule } from '@home/pages/trendz-settings/trendz-settings.module'; import { AgentModule } from '@home/pages/agent/agent.module'; import { IotHubModule } from '@home/pages/iot-hub/iot-hub.module'; +import { AiAssistantModule } from '@home/pages/ai-assistant/ai-assistant.module'; @NgModule({ exports: [ AdminModule, - HomeLinksModule, + HomePageModule, ProfileModule, SecurityModule, TenantProfileModule, @@ -94,7 +94,6 @@ import { IotHubModule } from '@home/pages/iot-hub/iot-hub.module'; IFrameViewModule, SchedulerModule, OtaUpdateModule, - SolutionCreatorModule, VcModule, TaskManagerModule, AccountModule, @@ -105,7 +104,8 @@ import { IotHubModule } from '@home/pages/iot-hub/iot-hub.module'; ReportingModule, TrendzAnalyticsModule, TrendzSettingsModule, - IotHubModule + IotHubModule, + AiAssistantModule ] }) export class HomePagesModule { } diff --git a/ui-ngx/src/app/modules/home/pages/integration/integrations-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/integration/integrations-table-config.resolver.ts index 6babb97851..e03867999e 100644 --- a/ui-ngx/src/app/modules/home/pages/integration/integrations-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/integration/integrations-table-config.resolver.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { DestroyRef, Injectable } from '@angular/core'; +import { DestroyRef, inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; +import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { EntityTableConfig } from '@home/models/entity/entities-table-config.models'; import { TranslateService } from '@ngx-translate/core'; @@ -21,10 +23,13 @@ import { MatDialog } from '@angular/material/dialog'; import { IntegrationsTableConfig } from '@home/pages/integration/integrations-table-config'; import { PageLink } from '@shared/models/page/page-link'; import { EntityDebugSettingsService } from '@home/components/entity/debug/entity-debug-settings.service'; +import { EdgeId } from '@shared/models/id/edge-id'; @Injectable() export class IntegrationsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private integrationService: IntegrationService, private userPermissionsService: UserPermissionsService, private edgeService: EdgeService, @@ -39,7 +44,15 @@ export class IntegrationsTableConfigResolver { } resolve(route: ActivatedRouteSnapshot): EntityTableConfig { - return this.resolveIntegrationsTableConfig(resolveIntegrationParams(route)); + const config = this.resolveIntegrationsTableConfig(resolveIntegrationParams(route)); + const scope = config.componentsData.integrationScope; + config.aiAssistantConfig = scope === 'edges' + ? this.aiAssistantConfigService.tableConfig(AiAssistantViewType.INTEGRATION_TEMPLATE_LIST, AiAssistantViewType.INTEGRATION_TEMPLATE) + : scope === 'edge' + ? this.aiAssistantConfigService.tableConfig(AiAssistantViewType.INTEGRATION_TEMPLATE_LIST, AiAssistantViewType.INTEGRATION_TEMPLATE, + new EdgeId(config.componentsData.edgeId)) + : this.aiAssistantConfigService.tableConfig(AiAssistantViewType.INTEGRATION_LIST, AiAssistantViewType.INTEGRATION); + return config; } resolveIntegrationsTableConfig(params: IntegrationParams): EntityTableConfig { diff --git a/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts b/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts index 8fc77b3bce..9f7634a9e5 100644 --- a/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts +++ b/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts @@ -17,6 +17,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { ActivatedRoute } from '@angular/router'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { switchMap } from 'rxjs/operators'; @Component({ selector: 'tb-mobile-qr-code-widget', @@ -55,8 +57,18 @@ export class MobileQrCodeWidgetSettingsComponent extends PageComponent implement private mobileAppService: MobileApplicationService, private fb: FormBuilder, private userPermissionsService: UserPermissionsService, - private route: ActivatedRoute) { + private route: ActivatedRoute, + private aiAssistantPanelService: AiAssistantPanelService) { super(store); + this.aiAssistantPanelService.customizationReload$('MOBILE_QR_CODE', () => !this.mobileAppSettingsForm.dirty).pipe( + switchMap(() => this.mobileAppService.getMobileAppSettings({ignoreLoading: true})), + takeUntilDestroyed() + ).subscribe(settings => { + if (settings.qrCodeConfig?.showOnHomePage !== this.mobileAppSettings?.qrCodeConfig?.showOnHomePage) { + this.store.dispatch(new ActionUpdateMobileQrCodeEnabled({mobileQrEnabled: settings.qrCodeConfig?.showOnHomePage})); + } + this.processMobileAppSettings(settings); + }); if (this.readonly) { this.mobileAppSettingsForm.disable() } else { diff --git a/ui-ngx/src/app/modules/home/pages/notification/recipient/recipient-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/notification/recipient/recipient-table-config.resolver.ts index f560ef8baf..ab06e1954d 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/recipient/recipient-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/notification/recipient/recipient-table-config.resolver.ts @@ -25,7 +25,8 @@ import { } from '@home/pages/notification/recipient/recipient-notification-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRouteSnapshot } from '@angular/router'; -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { DatePipe } from '@angular/common'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { Observable } from 'rxjs'; @@ -37,6 +38,8 @@ export class RecipientTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private panelService = inject(AiAssistantPanelService); + constructor(private store: Store, private notificationService: NotificationService, private translate: TranslateService, @@ -93,7 +96,8 @@ export class RecipientTableConfigResolver { private editTarget($event: Event, target: NotificationTarget): void { $event?.stopPropagation(); - this.notificationTargetDialog(target).subscribe(res => res ? this.config.updateData() : null); + this.panelService.focusWhile({type: AiAssistantViewType.NOTIFICATION_RECIPIENT, entityId: target?.id}, target?.name, + this.notificationTargetDialog(target)).subscribe(res => res ? this.config.updateData() : null); } private notificationTargetDialog(target: NotificationTarget, isAdd = false): Observable { diff --git a/ui-ngx/src/app/modules/home/pages/notification/rule/rule-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/notification/rule/rule-table-config.resolver.ts index 784ffb5179..99837f1e59 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/rule/rule-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/notification/rule/rule-table-config.resolver.ts @@ -26,7 +26,8 @@ import { RuleNotificationDialogData } from '@home/pages/notification/rule/rule-notification-dialog.component'; import { ActivatedRouteSnapshot } from '@angular/router'; -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { DatePipe } from '@angular/common'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { Observable } from 'rxjs'; @@ -38,6 +39,8 @@ export class RuleTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private panelService = inject(AiAssistantPanelService); + constructor(private store: Store, private notificationService: NotificationService, private translate: TranslateService, @@ -115,7 +118,8 @@ export class RuleTableConfigResolver { private editRule($event: Event, rule: NotificationRule, isCopy = false): void{ $event?.stopPropagation(); - this.notificationRuleDialog(rule, false, isCopy).subscribe(res => res ? this.config.updateData() : null); + this.panelService.focusWhile({type: AiAssistantViewType.NOTIFICATION_RULE, entityId: (isCopy ? undefined : rule)?.id}, rule?.name, + this.notificationRuleDialog(rule, false, isCopy)).subscribe(res => res ? this.config.updateData() : null); } private notificationRuleDialog(rule: NotificationRule, isAdd = false, isCopy = false): Observable { diff --git a/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts b/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts index 44ef33c4fb..84f759fe67 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts +++ b/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts @@ -22,6 +22,9 @@ import { NotificationService } from '@core/http/notification.service'; import { DialogService } from '@core/services/dialog.service'; import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { switchMap } from 'rxjs/operators'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; type NotificationSettingRow = NotificationUserSetting & { name: string }; @@ -55,8 +58,13 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn private notificationService: NotificationService, private fb: UntypedFormBuilder, private userPermissionsService: UserPermissionsService, + private aiAssistantPanelService: AiAssistantPanelService, ) { super(store); + this.aiAssistantPanelService.customizationReload$('ACCOUNT_NOTIFICATIONS', () => !this.notificationSettings?.dirty && !!this.notificationDeliveryMethods).pipe( + switchMap(() => this.notificationService.getNotificationUserSettings({ignoreLoading: true})), + takeUntilDestroyed() + ).subscribe(settings => this.patchNotificationSettings(settings)); this.notificationService.getAvailableDeliveryMethods({ignoreLoading: true}).subscribe( allowMethods => { this.notificationDeliveryMethods = allowMethods.filter(value => !this.deliveryMethods.has(value)); diff --git a/ui-ngx/src/app/modules/home/pages/notification/template/template-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/notification/template/template-table-config.resolver.ts index 1e46528e77..e6b07cd025 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/template/template-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/notification/template/template-table-config.resolver.ts @@ -24,7 +24,8 @@ import { TemplateNotificationDialogData } from '@home/pages/notification/template/template-notification-dialog.component'; import { TranslateService } from '@ngx-translate/core'; -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { ActivatedRouteSnapshot } from '@angular/router'; import { DatePipe } from '@angular/common'; import { Observable } from 'rxjs'; @@ -40,6 +41,8 @@ export class TemplateTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private panelService = inject(AiAssistantPanelService); + constructor(private store: Store, private notificationService: NotificationService, private translate: TranslateService, @@ -114,7 +117,8 @@ export class TemplateTableConfigResolver { private editTemplate($event: Event, template: NotificationTemplate, isCopy = false) { $event?.stopPropagation(); - this.notificationTemplateDialog(template, false, isCopy).subscribe((res) => res ? this.config.updateData() : null); + this.panelService.focusWhile({type: AiAssistantViewType.NOTIFICATION_TEMPLATE, entityId: (isCopy ? undefined : template)?.id}, template?.name, + this.notificationTemplateDialog(template, false, isCopy)).subscribe((res) => res ? this.config.updateData() : null); } private notificationTemplateDialog(template: NotificationTemplate, isAdd = false, isCopy = false): Observable { diff --git a/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts b/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts index 3e5f45ab58..e624653f47 100644 --- a/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts +++ b/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts @@ -21,6 +21,9 @@ import { UnitSystem, UnitSystems } from '@shared/models/unit.models'; import { UnitService } from '@core/services/unit.service'; import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { switchMap } from 'rxjs/operators'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({ selector: 'tb-profile', @@ -45,8 +48,13 @@ export class ProfileComponent extends PageComponent implements OnInit, HasConfir private unitService: UnitService, private fb: UntypedFormBuilder, private userPermissionsService: UserPermissionsService, + private aiAssistantPanelService: AiAssistantPanelService, ) { super(store); + this.aiAssistantPanelService.customizationReload$('PROFILE', () => !this.profile?.dirty).pipe( + switchMap(() => this.userService.getUser(this.user.id.id, {ignoreLoading: true})), + takeUntilDestroyed() + ).subscribe(user => this.userLoaded(user)); } ngOnInit() { diff --git a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.html b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.html index b27faf6eeb..8dcce8c63b 100644 --- a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.html +++ b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.html @@ -30,6 +30,7 @@
+ +
+
+
+ @for (k of steps(); track k) { + @if (k) { +
{{ 'tour.invite.kicker' | translate: {kicker: ('tour.invite.kicker-' + person | translate), step: k, count: cards} }}
+

{{ 'tour.invite.card-' + k + '.title' | translate }}

+

{{ 'tour.invite.card-' + k + '.lead' | translate }}

+ } @else { +

{{ ('tour.invite.pill-' + person | translate) + ': ' + ('tour.invite.news' | translate) + ' ' + ('tour.invite.cover-title' | translate) }}

+

{{ 'tour.invite.cover-lead' | translate }}

+ } +
+ @if (k) { + + @for (n of cardNumbers; track n) { + + } + + } @else if (person === 'before') { +

{{ 'tour.invite.note' | translate }}

+ } +
+ @if (k) { + + } @else { + + } + +
+
+ } +
+
diff --git a/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss b/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss new file mode 100644 index 0000000000..c4a86e92b0 --- /dev/null +++ b/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss @@ -0,0 +1,389 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-invite-backdrop { + background: rgba(16, 24, 40, 0.28); + -webkit-backdrop-filter: blur(6px) saturate(1.1); + backdrop-filter: blur(6px) saturate(1.1); +} + +.tb-invite-panel { + width: 720px; + max-width: calc(100vw - 32px) !important; + + .mat-mdc-dialog-container { + padding: 0; + } + + .mat-mdc-dialog-surface { + overflow: visible; + border-radius: 24px; + background: transparent; + box-shadow: none; + } +} + +@media (max-width: 640px) { + .tb-invite-panel { + width: 100vw; + max-width: 100vw !important; + height: 100dvh; + max-height: 100dvh !important; + + .mat-mdc-dialog-surface { + overflow: auto; + border-radius: 0; + } + } +} + +.tb-invite { + --tb-widget-shadow: 0 1px 1px rgba(20, 52, 58, 0.06), 0 2px 6px -1px rgba(20, 52, 58, 0.08); + --tb-widget-radius: 12px; + + .iv-x.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 36px; + --mat-icon-button-state-layer-size: 36px; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 6px; + } + + .iv-go { + --mat-button-filled-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); + } + + .ai-field { + position: relative; + overflow: hidden; + isolation: isolate; + background: var(--ai-field-wash); + } + + .ai-field[data-level="tile"] { + background: var(--ai-field-tile); + } + + .ai-field[data-motion="live"]::after { + content: ''; + position: absolute; + inset: -30%; + z-index: -1; + pointer-events: none; + background: var(--ai-field-wash); + opacity: 0.6; + filter: blur(24px); + will-change: transform; + animation: iv-drift 28s ease-in-out infinite alternate; + } +} + +@keyframes iv-drift { + 0% { transform: translate(-3%, -2%); } + 50% { transform: translate(3%, 2%); } + 100% { transform: translate(-1%, 3%); } +} + +.tb-invite { position: relative; width: 100%; overflow: hidden; border-radius: 24px; background: var(--tb-surface); color: var(--tb-ink); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 24px 48px -12px rgba(16, 24, 40, 0.22), 0 48px 96px -24px rgba(16, 24, 40, 0.24); + } +.tb-invite .iv-top { position: relative; } +.tb-invite .iv-version { display: inline-flex; align-items: center; gap: 6px; font: 500 15px/20px var(--tb-font); letter-spacing: 0; color: var(--tb-ink-76); } +.tb-invite .iv-version .mat-icon { font-size: 16px; width: 16px; height: 16px; color: var(--ai-action); } +.tb-invite .iv-x { position: absolute; top: 12px; right: 12px; z-index: 3; width: 36px; height: 36px; border-radius: 50%; background: rgb(255 255 255 / 0.72); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); color: var(--tb-ink-76); } +.iv-canvas { height: 340px; -webkit-mask-image: linear-gradient(to bottom, #000 82%, transparent); mask-image: linear-gradient(to bottom, #000 82%, transparent); } +.iv-window { position: absolute; z-index: 1; left: 12%; right: 12%; top: 120px; height: 300px; display: grid; grid-template-columns: 31% 1fr; overflow: hidden; border-radius: 14px; background: var(--tb-surface); + box-shadow: 0 0 0 1px rgb(16 24 40 / 0.06), 0 24px 48px -20px rgb(16 24 40 / 0.3), 0 8px 16px -8px rgb(16 24 40 / 0.12); font-family: var(--tb-font); + transition: translate .5s cubic-bezier(.16, 1, .3, 1); animation: iv-rise .6s cubic-bezier(.16, 1, .3, 1) .08s both; } +@keyframes iv-rise { from { opacity: 0; transform: translateY(28px); } } +@keyframes iv-pop { from { opacity: 0; transform: translateY(6px) scale(.98); } } +.tb-invite .iv-body { padding: 28px 32px 24px; } +.tb-invite .iv-title { margin: 0; font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); letter-spacing: 0; color: var(--tb-ink); text-wrap: balance; } +.tb-invite .iv-grad { background: linear-gradient(90deg in oklab, var(--ai-action), var(--ai-teal-600)); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; } +.tb-invite .iv-lead { margin: 6px 0 0; max-width: 560px; font: 400 15px/22px var(--tb-font); color: var(--tb-ink-76); text-wrap: pretty; } +.tb-invite .iv-foot { display: flex; align-items: center; gap: 16px; margin-top: 28px; padding-top: 16px; border-top: 1px solid var(--tb-line-soft); } +.tb-invite .iv-note { flex: 1; margin: 0; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.tb-invite .iv-actions { display: flex; gap: 8px; flex: none; margin-left: auto; } +.tb-invite .iv-actions .mdc-button { height: 36px; padding: 0 16px; border-radius: 8px; } +@media (max-width: 640px) { + .tb-invite:not(.iv-static) { display: flex; flex-direction: column; width: 100%; min-height: 100dvh; overflow: visible; border-radius: 0; box-shadow: none; animation-name: iv-up; } + .tb-invite:not(.iv-static) .iv-top { flex: none; } + @keyframes iv-up { from { opacity: 0; transform: translateY(32px); } } + .tb-invite:not(.iv-static) .iv-top { height: clamp(300px, 50dvh, 440px); } + .tb-invite:not(.iv-static) .iv-window { left: 6%; right: 6%; top: calc(150px + env(safe-area-inset-top)); } + .tb-invite:not(.iv-static) .iv-window.rq-files-w { left: 5%; right: 5%; top: calc(60px + env(safe-area-inset-top)); height: min(332px, calc(100% - 72px)); } + .tb-invite:not(.iv-static) .rq-files-w .rq-fgroup.in, .tb-invite:not(.iv-static) .rq-files-w .rq-fgroup small { display: none; } + .tb-invite:not(.iv-static) .rq-files-w .rq-fgrid { height: auto; padding: 12px; } + .tb-invite:not(.iv-static) .rq-files-w .rq-ftiles { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .tb-invite:not(.iv-static) .rq-files-w .rq-ft:nth-child(n+4) { display: none; } + .tb-invite:not(.iv-static) .rq-files-w .rq-code { top: 102px; left: 0; width: auto; box-shadow: none; translate: 0 102%; } + .tb-invite:not(.iv-static) .rq-files-w.open .rq-code { translate: 0 0; } + .tb-invite:not(.iv-static) .iv-window.rq-dock { left: 5%; right: 5%; top: calc(60px + env(safe-area-inset-top)); grid-template-columns: 1fr; } + .tb-invite:not(.iv-static) .rq-dock .iv-sk-page { display: none; } + .tb-invite:not(.iv-static) .iv-window.rq-col { left: 5%; right: 5%; top: calc(60px + env(safe-area-inset-top)); padding: 16px; } + .tb-invite:not(.iv-static) .rq-review { width: 320px; margin-left: -160px; } + .tb-invite:not(.iv-static) .rq-ask { top: calc(64px + env(safe-area-inset-top)); width: 328px; margin-left: -164px; } + .tb-invite:not(.iv-static) .rq-hero { padding: calc(40px + env(safe-area-inset-top)) 20px 0; } + .tb-invite:not(.iv-static) .iv-x { top: calc(10px + env(safe-area-inset-top)); right: 10px; } + .tb-invite:not(.iv-static) .iv-body { flex: 1 0 auto; display: flex; flex-direction: column; padding: 20px 20px 0; } + .tb-invite:not(.iv-static) .iv-foot { position: sticky; bottom: 0; margin-top: auto; flex-direction: column; align-items: stretch; gap: 12px; padding: 16px 0 calc(16px + env(safe-area-inset-bottom)); background: var(--tb-surface); } + .tb-invite:not(.iv-static) .iv-actions { flex-direction: column-reverse; gap: 4px; margin-left: 0; } + .tb-invite:not(.iv-static) .iv-dotsnav { flex: none; justify-content: center; padding: 2px 0 4px; } + .tb-invite:not(.iv-static) .iv-actions .mdc-button { width: 100%; height: 44px; justify-content: center; } + .tb-invite:not(.iv-static) .iv-note { order: -1; } +} +@media (prefers-reduced-motion: reduce) { + .tb-invite, .tb-invite * { animation: none !important; } + .iv-window { transition: none; } +} +.tb-invite .iv-top { position: relative; height: 340px; } +.tb-invite .iv-scene { position: absolute; inset: 0; height: auto; opacity: 0; visibility: hidden; transition: opacity .3s ease, visibility 0s linear .3s; } +.tb-invite .iv-scene.on { opacity: 1; visibility: visible; transition: none; animation: iv-scene-in .4s ease both; } +@keyframes iv-scene-in { from { opacity: 0; } } +.tb-invite .iv-body { min-height: 196px; display: flex; flex-direction: column; } +.tb-invite .iv-body > * { animation: iv-fade .3s ease both; } +@keyframes iv-fade { from { opacity: 0; transform: translateY(4px); } } +.tb-invite .iv-kicker { margin-bottom: 6px; font: 500 12px/16px var(--tb-font); letter-spacing: .4px; text-transform: uppercase; color: var(--tb-text-secondary); } +.tb-invite .iv-foot { margin-top: auto; } +.tb-invite .iv-lead { margin-bottom: 24px; } +.tb-invite .iv-kicker ~ .iv-lead { min-height: 3lh; } +.iv-dotsnav { flex: 1; display: inline-flex; align-items: center; gap: 6px; } +.iv-dotsnav i { width: 6px; height: 6px; border-radius: 3px; background: var(--tb-line); transition: width .25s cubic-bezier(.16, 1, .3, 1), background-color .25s ease; } +.iv-dotsnav i.on { width: 18px; background: var(--ai-action); } +@media (prefers-reduced-motion: reduce) { .tb-invite .iv-scene, .tb-invite .iv-scene.on, .iv-dotsnav i { transition: none; } } +.iv-tone { overflow: hidden; background: var(--ai-light-paper); } +.iv-tone[data-tone="aqua"] { background: radial-gradient(90% 120% at 0% 0%, var(--ai-light-aqua), transparent 70%), radial-gradient(80% 110% at 100% 100%, color-mix(in oklab, var(--ai-light-teal) 75%, transparent), transparent 70%), var(--ai-light-paper); } +.iv-tone[data-tone="amber"] { background: radial-gradient(90% 120% at 0% 0%, var(--ai-light-amber), transparent 70%), radial-gradient(80% 110% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) 80%, transparent), transparent 70%), var(--ai-light-paper); } +.iv-tone[data-tone="lilac"] { background: radial-gradient(100% 130% at 0% 0%, var(--ai-light-lilac), transparent 72%), radial-gradient(70% 100% at 100% 100%, color-mix(in oklab, var(--ai-light-lilac) 55%, transparent), transparent 70%), var(--ai-light-paper); } +.iv-tone[data-tone="teal"] { background: radial-gradient(90% 120% at 0% 0%, var(--ai-light-teal), transparent 70%), radial-gradient(80% 110% at 100% 100%, color-mix(in oklab, var(--ai-light-mint) 80%, transparent), transparent 70%), var(--ai-light-paper); } +.iv-sk-page { display: flex; flex-direction: column; min-width: 0; } +.iv-sk-row { display: flex; gap: 8px; } +.rq-sp { flex: 1; } +.rq-typing { display: block; min-height: 24px; } +.rq-typing.sent { animation: rq-sent .2s cubic-bezier(.3, 0, .8, .15) both; } +@keyframes rq-sent { to { opacity: 0; transform: translateY(-12px); } } +.rq-caret { display: inline-block; width: 2px; height: 20px; margin-left: 1px; border-radius: 1px; background: var(--ai-action); vertical-align: -4px; animation: rq-blink 1.06s step-end infinite; } +@keyframes rq-blink { 50% { opacity: 0; } } +.iv-canvas.iv-tone { -webkit-mask-image: linear-gradient(to bottom, #000 90%, transparent); mask-image: linear-gradient(to bottom, #000 90%, transparent); } +.rq-hero { position: absolute; inset: 0 0 4px; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 0 72px; font-family: var(--tb-font); + animation: iv-rise .6s cubic-bezier(.16, 1, .3, 1) .05s both; } +.rq-hero-t { display: flex; flex-direction: column; align-items: center; margin: 8px 0 14px; font: 500 30px/38px var(--tb-font); letter-spacing: -0.4px; color: var(--tb-ink); text-align: center; text-wrap: balance; } +.rq-hero .rq-term { align-self: stretch; } +.rq-term { border-radius: 14px; background: var(--tb-surface); 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); font-family: var(--tb-font); } +.rq-term.focus { box-shadow: 0 0 0 2px var(--ai-focus), 0 8px 24px var(--ai-focus-shadow); } +.rq-term.focus .rq-pre { color: var(--ai-focus); } +.rq-term-in { display: flex; align-items: flex-start; gap: 10px; min-height: 48px; padding: 12px 10px 10px 16px; } +.rq-term-in .rq-pre { flex: none; width: 18px; height: 24px; font-size: 20px; line-height: 24px; color: var(--ai-action); } +.rq-term-words { position: relative; flex: 1; min-width: 0; min-height: 24px; font: 400 16px/24px var(--tb-font); color: var(--tb-ink); text-align: left; } +.rq-ph { color: var(--tb-text-muted); } +.rq-send { flex: none; align-self: flex-end; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 10px; background: var(--ai-action); color: var(--ai-on-action, #fff); transition: background-color .2s ease, color .2s ease, transform .14s ease; } +.rq-send.off { background: color-mix(in oklab, var(--tb-ink) 6%, var(--tb-surface)); color: var(--tb-ink-38); } +.rq-send.press { transform: scale(.86); } +.rq-send .mat-icon { font-size: 18px; width: 18px; height: 18px; } +.rq-term-foot { display: flex; align-items: center; gap: 2px; padding: 2px 8px 6px; border-top: 1px solid var(--tb-line-soft); font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-tool { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; } +.rq-tool .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-ink-54); } +.rq-term.compact .rq-term-in { min-height: 0; padding: 10px 8px 10px 12px; } +.rq-term.compact .rq-send { align-self: center; width: 32px; height: 32px; } +.rq-term.compact .rq-pre { height: 22px; line-height: 22px; } +.rq-term.compact .rq-term-words { font-size: 14px; line-height: 22px; } +.iv-window.rq-dock { top: 20px; left: 6%; right: 6%; height: 284px; grid-template-columns: 1fr 56%; } +.rq-dash { display: flex; flex-direction: column; gap: 12px; padding: 16px; } +.rq-companion { display: flex; flex-direction: column; border-left: 1px solid var(--tb-line); background: var(--tb-surface); font-family: var(--tb-font); } +.rq-chead { display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 8px 6px 12px; border-bottom: 1px solid var(--tb-line-soft); } +.rq-chead b { font: 500 14px/20px var(--tb-font); } +.rq-chead > .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-ink-54); } +.rq-empty { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 14px 14px 0; text-align: center; } +.rq-empty > b { font: 500 15px/22px var(--tb-font); } +.rq-empty > .tb-ai-mark { margin-bottom: 6px; } +.rq-empty > span { font: 400 12.5px/18px var(--tb-font); color: var(--tb-text-secondary); } +.rq-prompts { align-self: stretch; display: flex; flex-direction: column; margin-top: 10px; border-top: 1px solid var(--tb-line); text-align: left; } +.rq-prompt { display: grid; grid-template-columns: 18px 1fr; align-items: center; gap: 10px; min-height: 40px; padding: 0 6px; border-bottom: 1px solid var(--tb-line); font: 400 13.5px/20px var(--tb-font); color: var(--tb-ink); } +.rq-prompt .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-ink-54); } +.rq-companion .rq-term { margin: 10px 12px 12px; } +.rq-dock .rq-chead { min-height: 44px; } +.rq-dock .rq-empty { gap: 2px; padding-top: 10px; } +.rq-dock .rq-empty > .tb-ai-mark { --m: 28px; margin-bottom: 4px; } +.rq-dock .rq-prompts { margin-top: 8px; } +.rq-dock .rq-prompt { min-height: 36px; } +.rq-dock .rq-term.compact .rq-term-in { padding: 8px 8px 8px 12px; } +.rq-companion .rq-term.docked { margin: 0; border-top: 1px solid var(--tb-line); border-radius: 0; box-shadow: none; } +.rq-dock .rq-term.docked .rq-term-in { padding: 10px 10px 2px 14px; } +.rq-term.docked .rq-term-foot { padding: 0 6px 4px; border-top: 0; } +.rq-term.docked .rq-tool { width: 30px; height: 30px; } +.iv-canvas.iv-sky { -webkit-mask-image: linear-gradient(to bottom, #000 84%, transparent); mask-image: linear-gradient(to bottom, #000 84%, transparent); } +.rq-home { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: flex-start; padding: 26px 56px 0; font-family: var(--tb-font); + animation: iv-rise .6s cubic-bezier(.16, 1, .3, 1) .05s both; } +.rq-hdate { font: 500 12px/16px var(--tb-font); letter-spacing: .5px; text-transform: uppercase; color: var(--tb-ink-54); } +.rq-hgreet { display: flex; align-items: center; gap: 8px; margin-top: 2px; font: 600 24px/32px var(--tb-font); letter-spacing: -0.2px; color: var(--tb-ink); } +.rq-hgreet .tb-ai-mark { --m: 34px; width: calc(var(--m) * var(--ai-spark)); height: calc(var(--m) * var(--ai-spark)); border-radius: 0; background: none; box-shadow: none; animation: none; } +.rq-hpills { display: flex; gap: 8px; margin-top: 10px; } +.rq-hpill { display: inline-flex; align-items: center; gap: 8px; height: 30px; padding: 0 14px; border-radius: 15px; background: var(--tb-surface); box-shadow: var(--tb-widget-shadow); font: 400 14px/20px var(--tb-font); color: var(--tb-ink); white-space: nowrap; } +.rq-hpill .mat-icon { margin-left: -3px; font-size: 16px; width: 16px; height: 16px; color: var(--tb-crit); } +.rq-hrow { align-self: stretch; display: flex; gap: 8px; max-width: 520px; margin-top: 12px; } +.rq-hfield { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; height: 46px; padding: 0 8px 0 16px; border-radius: var(--tb-widget-radius); background: var(--tb-surface); box-shadow: var(--tb-widget-shadow); transition: box-shadow .2s ease; } +.rq-hfield .rq-pre { flex: none; width: 18px; font-size: 20px; line-height: 24px; color: var(--ai-action); } +.rq-hfield .rq-typing { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; font: 400 16px/24px var(--tb-font); color: var(--tb-ink); text-align: left; } +.rq-hkey { flex: none; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; min-width: 22px; height: 22px; margin-right: 8px; padding: 0 6px; border: 1px solid var(--tb-line); border-radius: 6px; font: 500 12px/1 var(--tb-font); color: var(--tb-ink-54); } +.rq-hfield .rq-send { display: none; align-self: center; width: 32px; height: 32px; } +.rq-hrow.typing .rq-hfield { box-shadow: 0 0 0 2px var(--ai-focus), 0 8px 24px var(--ai-focus-shadow); } +.rq-hrow.typing .rq-hfield .rq-pre { color: var(--ai-focus); } +.rq-hrow.typing .rq-hkey { display: none; } +.rq-hrow.typing .rq-send { display: inline-flex; } +.rq-hchats { flex: none; display: inline-flex; align-items: center; gap: 8px; box-sizing: border-box; height: 46px; max-width: 160px; padding: 0 12px 0 16px; overflow: hidden; white-space: nowrap; border-radius: var(--tb-widget-radius); box-shadow: inset 0 0 0 1px var(--tb-line); font: 500 14px/20px var(--tb-font); color: var(--tb-ink-76); + transition: max-width .25s ease, padding .25s ease, margin .25s ease, opacity .15s ease; } +.rq-hchats .mat-icon { flex: none; font-size: 20px; width: 20px; height: 20px; color: var(--tb-ink-76); } +.rq-hchats .mat-icon:last-child { margin-left: -4px; font-size: 16px; width: 16px; height: 16px; color: var(--tb-ink-54); } +.rq-hrow.typing .rq-hchats { max-width: 0; margin-left: -8px; padding: 0; opacity: 0; } +.rq-hwait { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin-top: 12px; } +.rq-hwait > small { font: 500 13px/18px var(--tb-font); letter-spacing: .1px; color: var(--tb-ink-76); } +.rq-hchatrow { display: flex; gap: 8px; } +.rq-hchat { display: inline-flex; align-items: center; gap: 8px; height: 36px; padding: 0 14px 0 12px; border-radius: var(--tb-widget-radius); background: var(--tb-surface); box-shadow: var(--tb-widget-shadow); white-space: nowrap; } +.rq-hchat i { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--tb-caution); } +.rq-hchat b { font: 500 14px/20px var(--tb-font); color: var(--tb-ink); } +.rq-hchat small { font: 400 13px/18px var(--tb-font); color: var(--tb-ink-54); } +.rq-hcards { align-self: stretch; display: grid; grid-template-columns: minmax(0, 1fr) 216px; gap: 12px; margin-top: 16px; } +.rq-hcard { display: flex; flex-direction: column; gap: 10px; height: 120px; padding: 12px 16px; border-radius: var(--tb-widget-radius) var(--tb-widget-radius) 0 0; background: var(--tb-surface); box-shadow: var(--tb-widget-shadow); } +.rq-hcard b { display: flex; align-items: center; gap: 8px; font: 500 15px/22px var(--tb-font); color: var(--tb-ink); } +.rq-hcard b .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-ink-76); } +.rq-hcard b small { font: 400 13px/18px var(--tb-font); color: var(--tb-ink-54); } +.rq-hcard i { display: block; height: 8px; border-radius: 4px; background: var(--tb-line); } +@media (max-width: 640px) { + .tb-invite:not(.iv-static) .rq-home { padding: calc(24px + env(safe-area-inset-top)) 20px 0; } + .tb-invite:not(.iv-static) .rq-hpills { flex-wrap: wrap; } + .tb-invite:not(.iv-static) .rq-hchats > span:not(.mat-icon) { display: none; } + .tb-invite:not(.iv-static) .rq-hchat:nth-child(n+2), .tb-invite:not(.iv-static) .rq-hcard:nth-child(n+2) { display: none; } + .tb-invite:not(.iv-static) .rq-hcards { grid-template-columns: 1fr; } +} +@media (prefers-reduced-motion: reduce) { .rq-hfield, .rq-hchats { transition: none; } } +.iv-window.rq-col { display: flex; flex-direction: column; top: 22px; left: 19%; right: 19%; height: 276px; gap: 12px; padding: 18px 22px; font-family: var(--tb-font); } +.rq-user { align-self: flex-end; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; max-width: 85%; } +.rq-bubble { padding: 10px 14px; border-radius: 16px 16px 4px 16px; background: var(--ai-person); font: 400 14px/20px var(--tb-font); color: var(--tb-ink); } +.rq-hero .rq-bubble { background: var(--tb-surface); } +.rq-hero :is(.rq-rec, .rq-file) { border-color: transparent; } +.rq-files { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; } +.rq-agent { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; } +.rq-agent p { margin: 0; font: 400 14px/21px var(--tb-font); color: var(--tb-ink); } +.rq-rec { display: grid; grid-template-columns: 24px auto 1fr auto; align-items: center; column-gap: 8px; min-height: 34px; padding: 4px 10px 4px 5px; border: 1px solid var(--tb-line); border-radius: 8px; background: var(--tb-surface); max-width: 100%; } +.rq-rec b { font: 500 13.5px/20px var(--tb-font); white-space: nowrap; } +.rq-rec small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-rec-tile { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 6px; } +.rq-rec-tile .mat-icon { font-size: 16px; width: 16px; height: 16px; } +.rq-rec.planned .rq-rec-tile { background: none !important; box-shadow: inset 0 0 0 1.5px currentColor; outline: 0; border: 1.5px dashed currentColor; box-shadow: none; } +.rq-rec-ok { font-size: 16px !important; width: 16px; height: 16px; color: var(--ai-teal-600); } +.rq-rec-tile { transition: background-color .25s ease; } +.rq-file { display: inline-flex; align-items: center; gap: 8px; padding: 5px 12px 5px 6px; border: 1px solid var(--tb-line); border-radius: 8px; background: var(--tb-surface); } +.rq-file b { display: block; font: 500 13px/18px var(--tb-font); white-space: nowrap; } +.rq-file small { display: block; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); white-space: nowrap; } +.rq-file-ic { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 6px; } +.rq-file-ic .mat-icon { font-size: 17px; width: 17px; height: 17px; } +.rq-file-ic[data-tone="rule"] { background: var(--entity-rule-bg); color: var(--entity-rule-fg); } +.rq-review { position: absolute; z-index: 2; left: 50%; top: 84px; width: 380px; margin-left: -190px; display: flex; flex-direction: column; gap: 10px; padding: 14px 16px; border: 1px solid var(--tb-line); border-radius: 12px; background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 18px 40px -16px rgba(16, 24, 40, 0.28); font-family: var(--tb-font); animation: iv-rise .6s cubic-bezier(.16, 1, .3, 1) .08s both; } +.rq-rev-head { display: flex; align-items: center; gap: 6px; font: 500 14px/20px var(--tb-font); color: var(--ai-teal-500); } +.rq-rev-head .mat-icon { font-size: 18px; width: 18px; height: 18px; } +.rq-ask { top: 34px; width: 420px; margin-left: -210px; gap: 12px; } +.rq-ask .rq-rev-head { color: var(--tb-ink); } +.rq-ask .rq-rev-head .mat-icon { color: var(--tb-ink-54); } +.rq-ask .rq-rev-head small { margin-left: 4px; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-ask-q b { display: block; font: 500 14px/20px var(--tb-font); color: var(--tb-ink); } +.rq-ask-q span { display: block; font: 400 14px/20px var(--tb-font); color: var(--tb-text-secondary); } +.rq-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.rq-chip { display: inline-flex; align-items: center; height: 32px; padding: 0 14px; border-radius: 16px; box-shadow: inset 0 0 0 1px var(--tb-line); font: 400 14px/20px var(--tb-font); color: var(--tb-ink-76); white-space: nowrap; } +.rq-chip.on { box-shadow: inset 0 0 0 2px var(--ai-focus); font-weight: 500; color: var(--tb-ink); } +.rq-ask-hint { margin: -2px 0 0; font: 400 13px/18px var(--tb-font); color: var(--tb-text-secondary); } +.rq-ask .rq-actions { margin-top: 2px; } +.rq-ask .rq-actions .rq-sp { flex: 1; } +.rq-actions { display: flex; gap: 8px; margin-top: 2px; } +.rq-btn { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 14px 0 12px; border-radius: 8px; font: 500 14px/1 var(--tb-font); letter-spacing: .1px; } +.rq-btn .mat-icon { font-size: 18px; width: 18px; height: 18px; } +.rq-btn.fill { background: var(--ai-action); color: var(--ai-on-action, #fff); } +.rq-btn.text { color: var(--ai-action); } +.rq-chip { transition: box-shadow .16s ease, color .16s ease; } +.iv-window.rq-files-w { display: block; top: 22px; left: 7%; right: 7%; height: 276px; } +.rq-code { position: absolute; top: 0; right: 0; bottom: 0; width: 60%; display: flex; flex-direction: column; min-width: 0; background: var(--tb-code-bg); color: var(--tb-code-fg); + box-shadow: -16px 0 32px -16px rgb(16 24 40 / 0.45); translate: 102% 0; transition: translate .45s cubic-bezier(.16, 1, .3, 1); } +.rq-files-w.open .rq-code { translate: 0 0; } +.rq-code-head { display: flex; align-items: center; gap: 8px; height: 44px; padding: 0 10px 0 14px; border-bottom: 1px solid var(--tb-code-line); font-family: var(--tb-font); } +.rq-code-head > .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-code-head-fg); } +.rq-code-head b { font: 500 13.5px/20px var(--tb-font); color: var(--tb-code-fg); } +.rq-code-edit { padding: 3px 10px; border-radius: 6px; font: 500 12.5px/18px var(--tb-font); color: rgba(255, 255, 255, 0.72); box-shadow: inset 0 0 0 1px var(--tb-code-line); } +.rq-code-body { padding: 12px 0; font: 400 12.5px/21px var(--tb-mono); } +.rq-ln { display: grid; grid-template-columns: 34px 1fr; white-space: pre; } +.rq-ln i { padding-right: 12px; text-align: right; font-style: normal; color: rgba(255, 255, 255, 0.32); } +.rq-ln > span { overflow: hidden; text-overflow: ellipsis; } +.rq-ln:not(.w) { visibility: hidden; } +.rq-ln.w > span { animation: iv-fade .25s ease both; } +.rq-code .hl-key { color: var(--hl-key); } .rq-code .hl-cmd { color: var(--hl-cmd); } .rq-code .hl-str { color: var(--hl-str); } .rq-code .hl-num { color: var(--hl-num); } .rq-code .hl-flag { color: var(--hl-flag); } +.rq-wait { visibility: hidden; } +.rq-in { animation: iv-pop .35s cubic-bezier(.16, 1, .3, 1) both; } +.rq-pressed { scale: .97; } +.rq-cursor { position: absolute; left: 0; top: 0; z-index: 6; width: 22px; height: 22px; margin: -2px 0 0 -5px; opacity: 0; pointer-events: none; transform: translate(560px, 320px); + transition: transform .52s cubic-bezier(.3, .1, .2, 1), opacity .2s ease; filter: drop-shadow(0 1px 2px rgb(16 24 40 / 0.4)); } +.rq-cursor svg { display: block; width: 100%; height: 100%; fill: var(--tb-ink); stroke: #fff; stroke-width: 1.5; stroke-linejoin: round; transition: scale .12s ease; transform-origin: 20% 12%; } +.rq-cursor.on { opacity: 1; } +.rq-cursor.press svg { scale: .84; } +.tb-invite[data-step="0"] .iv-top { height: 432px; } +.tb-invite[data-step="0"] .iv-body { min-height: 163px; padding-top: 20px; } +.tb-invite[data-step="0"] .iv-lead { margin-bottom: 16px; } +.iv-canvas[data-scene="0"] { height: 432px; -webkit-mask-image: linear-gradient(to bottom, #000 92%, transparent); mask-image: linear-gradient(to bottom, #000 92%, transparent); } +.rq-log { align-self: stretch; height: 0; margin-top: -12px; display: flex; flex-direction: column; justify-content: flex-end; gap: 10px; transition: height .5s cubic-bezier(.16, 1, .3, 1), margin-top .5s cubic-bezier(.16, 1, .3, 1), opacity .2s ease; } +.rq-log.open { height: 124px; margin-top: 0; } +.rq-log.out { opacity: 0; } +.rq-log > *, .rq-log .rq-agent > * { animation: iv-pop .35s cubic-bezier(.16, 1, .3, 1) both; } +.rq-log .rq-agent .rq-rec { animation-delay: 0s; } +.rq-log .rq-agent p { text-align: left; } +.rq-ptop { display: flex; align-items: baseline; gap: 8px; height: 44px; padding: 0 14px; border-bottom: 1px solid var(--tb-line-soft); white-space: nowrap; } +.rq-ptop b { font: 500 14px/44px var(--tb-font); color: var(--tb-ink); } +.rq-ptop small { font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-dock .rq-dash { gap: 10px; padding: 12px 14px; } +.rq-tile { flex: 1; min-width: 0; padding: 8px 10px; border-radius: 8px; background: var(--tb-surface); box-shadow: inset 0 0 0 1px var(--tb-line-soft); } +.rq-tile small { display: block; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-tile b { display: block; font: 500 18px/24px var(--tb-font); color: var(--tb-ink); transition: color .3s ease; } +.rq-tile b .u { margin-left: 3px; font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-tile.hot b { color: var(--tb-caution); } +.rq-chart { height: 86px; padding: 8px 10px; border-radius: 8px; box-shadow: inset 0 0 0 1px var(--tb-line-soft); } +.rq-chart svg { display: block; width: 100%; height: 100%; overflow: visible; } +.rq-chart .lim { stroke: var(--tb-caution); stroke-width: 1; stroke-dasharray: 4 4; vector-effect: non-scaling-stroke; opacity: .75; } +.rq-chart .ln { fill: none; stroke: var(--ai-teal-600); stroke-width: 2; vector-effect: non-scaling-stroke; } +.rq-chart .plot { clip-path: inset(-20% 100% -20% 0); transition: clip-path 1s cubic-bezier(.4, 0, .2, 1); } +.rq-chart.drawn .plot { clip-path: inset(-20% 0 -20% 0); } +.rq-alarm { align-self: flex-start; display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px 0 8px; border-radius: 13px; background: color-mix(in oklab, var(--tb-caution) 12%, var(--tb-surface)); color: var(--tb-caution); font: 500 12px/16px var(--tb-font); white-space: nowrap; + opacity: 0; transform: translateY(4px); transition: opacity .25s ease, transform .25s ease; } +.rq-alarm.on { opacity: 1; transform: none; } +.rq-alarm .mat-icon { font-size: 15px; width: 15px; height: 15px; } +.rq-cbody { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.rq-cbody.said { gap: 10px; padding: 14px 14px 0; } +.rq-cbody.said .rq-bubble { padding: 8px 12px; } +.rq-prompt { transition: background-color .15s ease; } +.rq-prompt.picked { background: color-mix(in oklab, var(--ai-light-teal) 30%, transparent); } +.rq-agent.rq-plan { align-self: stretch; } +.rq-plan .rq-rec { align-self: stretch; } +.rq-plan-h { align-self: stretch; display: flex; align-items: center; gap: 8px; min-height: 30px; } +.rq-plan-h b { font: 500 14px/20px var(--tb-font); color: var(--tb-ink); } +.rq-plan-h small { font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-btn.sm { height: 28px; padding: 0 12px 0 8px; font-size: 13px; transition: background-color .2s ease, color .2s ease, opacity .2s ease; } +.rq-btn.sm.busy { padding: 0 12px; opacity: .72; } +.rq-btn.sm.done { background: none; color: var(--ai-teal-600); } +.rq-rec.made .rq-rec-ok { animation: iv-pop .3s cubic-bezier(.16, 1, .3, 1) both; } +.rq-said { display: none; align-items: center; gap: 6px; padding-bottom: 10px; border-bottom: 1px solid var(--tb-line-soft); font: 400 13px/18px var(--tb-font); color: var(--tb-text-secondary); } +.rq-said.on { display: flex; animation: iv-pop .3s cubic-bezier(.16, 1, .3, 1) both; } +.rq-said b { font-weight: 500; color: var(--tb-ink); } +.rq-said .mat-icon { font-size: 16px; width: 16px; height: 16px; color: var(--ai-teal-600); } +.rq-fgrid { box-sizing: border-box; height: 100%; display: flex; flex-direction: column; justify-content: center; gap: 16px; min-width: 0; padding: 0 16px; font-family: var(--tb-font); } +.rq-fgroup > small { display: block; margin-bottom: 6px; font: 500 12px/16px var(--tb-font); color: var(--tb-text-secondary); } +.rq-ftiles { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; } +.rq-ft { display: flex; flex-direction: column; align-items: center; gap: 6px; min-width: 0; padding: 8px 2px 6px; border-radius: 10px; transition: background-color .16s ease, box-shadow .16s ease, scale .1s ease; } +.rq-ft .rq-file-ic { width: 40px; height: 40px; border-radius: 10px; } +.rq-ft .rq-file-ic .mat-icon { font-size: 22px; width: 22px; height: 22px; } +.rq-ft b { max-width: 100%; overflow-wrap: anywhere; text-align: center; font: 500 12.5px/18px var(--tb-font); color: var(--tb-ink); } +.rq-ft.on { background: var(--ai-selected-wash); box-shadow: inset 0 0 0 2px var(--ai-selected); } +.rq-ft.on b { color: var(--ai-selected-text); } +@media (max-width: 640px) { + .tb-invite:not(.iv-static) .rq-hero-t { margin: 2px 0 6px; font-size: 26px; line-height: 32px; } + .tb-invite:not(.iv-static)[data-step="0"] .iv-top, .tb-invite:not(.iv-static) .iv-canvas[data-scene="0"] { height: 436px; } + .tb-invite:not(.iv-static) .rq-log.open { height: 112px; } + .tb-invite:not(.iv-static) .rq-hero { padding-top: calc(12px + env(safe-area-inset-top)); gap: 10px; } +} +@media (prefers-reduced-motion: reduce) { .rq-cursor { display: none; } .rq-chart .plot, .rq-alarm, .rq-log, .rq-tile b, .rq-ft, .rq-code { transition: none; } } diff --git a/ui-ngx/src/app/modules/tour/welcome-invitation.component.ts b/ui-ngx/src/app/modules/tour/welcome-invitation.component.ts new file mode 100644 index 0000000000..18aa9ae136 --- /dev/null +++ b/ui-ngx/src/app/modules/tour/welcome-invitation.component.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + computed, + ElementRef, + HostListener, + inject, + signal, + ViewChild, + ViewEncapsulation +} from '@angular/core'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { TranslateService } from '@ngx-translate/core'; +import { buildScene, CoverWords, SceneContext, WELCOME_CARDS } from '@modules/tour/welcome-scenes'; + +export type TourPerson = 'before' | 'new'; + +export interface WelcomeInvitationData { + person: TourPerson; +} + +export type WelcomeInvitationResult = 'tour' | 'later'; + +@Component({ + selector: 'tb-welcome-invitation', + templateUrl: './welcome-invitation.component.html', + styleUrls: ['./welcome-invitation.component.scss'], + encapsulation: ViewEncapsulation.None, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class WelcomeInvitationComponent implements AfterViewInit { + + @ViewChild('scenes', {static: true}) scenesRef: ElementRef; + + @ViewChild('go', {read: ElementRef}) goRef: ElementRef; + + private data = inject(MAT_DIALOG_DATA); + + private dialogRef = inject>(MatDialogRef); + + private translate = inject(TranslateService); + + readonly cards = WELCOME_CARDS; + + readonly cardNumbers = Array.from({length: WELCOME_CARDS}, (_, i) => i + 1); + + readonly person = this.data.person; + + readonly step = signal(0); + + readonly steps = computed(() => [this.step()]); + + private frames: HTMLElement[] = []; + + private readonly context: SceneContext = { + t: (key, params) => this.translate.instant(key, params), + locale: (this.translate.currentLang || 'en-US').replace('_', '-'), + still: typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches + }; + + private readonly coverWords: CoverWords = { + pill: this.translate.instant(`tour.invite.pill-${this.person}`), + news: this.translate.instant('tour.invite.news'), + title: this.translate.instant('tour.invite.cover-title') + }; + + ngAfterViewInit(): void { + const host = this.scenesRef.nativeElement; + for (let n = 0; n <= WELCOME_CARDS; n++) { + const frame = document.createElement('div'); + frame.className = 'iv-canvas iv-scene'; + frame.setAttribute('aria-hidden', 'true'); + host.append(frame); + this.frames.push(frame); + } + this.show(0); + } + + show(k: number): void { + if (k < 0 || k > WELCOME_CARDS) { + return; + } + this.step.set(k); + this.frames.forEach((frame, n) => { + if (n === k && !frame.classList.contains('on')) { + const fresh = buildScene(n, this.context, this.coverWords); + frame.replaceWith(fresh); + this.frames[n] = fresh; + fresh.classList.add('on'); + } else if (n !== k) { + frame.classList.remove('on'); + } + }); + setTimeout(() => this.goRef?.nativeElement.focus({preventScroll: true}), 30); + } + + next(): void { + if (this.step() === WELCOME_CARDS) { + this.dialogRef.close('tour'); + } else { + this.show(this.step() + 1); + } + } + + back(): void { + this.show(this.step() - 1); + } + + later(): void { + this.dialogRef.close('later'); + } + + @HostListener('document:keydown', ['$event']) + onKey(event: KeyboardEvent): void { + if (event.key === 'ArrowRight') { + this.show(this.step() + 1); + } else if (event.key === 'ArrowLeft') { + this.show(this.step() - 1); + } + } +} diff --git a/ui-ngx/src/app/modules/tour/welcome-scenes.ts b/ui-ngx/src/app/modules/tour/welcome-scenes.ts new file mode 100644 index 0000000000..a588ea8fec --- /dev/null +++ b/ui-ngx/src/app/modules/tour/welcome-scenes.ts @@ -0,0 +1,466 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export interface SceneContext { + t: (key: string, params?: Record) => string; + locale: string; + still: boolean; +} + +type Child = Node | string | null | undefined | false | Child[]; + +type Attrs = Record & { style?: string }; + +const ENTITY: Record = { + device: ['memory', 'device'], + dashboard: ['dashboard', 'view'], + rule: ['rule', 'rule'], + notification: ['notifications', 'people'] +}; + +const TONES = [null, 'sky', 'aqua', 'teal', 'amber', 'lilac']; + +const POINTER = ''; + +const CHART = '' + + ''; + +function append(el: HTMLElement, kids: Child[]): void { + for (const kid of kids) { + if (kid == null || kid === false) { + continue; + } + if (Array.isArray(kid)) { + append(el, kid); + } else { + el.append(kid); + } + } +} + +function h(tag: string, attrs: Attrs | null, ...kids: Child[]): HTMLElement { + const el = document.createElement(tag); + for (const [key, value] of Object.entries(attrs ?? {})) { + if (value != null) { + el.setAttribute(key, value); + } + } + append(el, kids); + return el; +} + +const q = (cls: string, ...kids: Child[]) => h('div', {class: cls}, ...kids); + +const icon = (name: string, cls?: string) => h('span', {class: 'mat-icon material-icons-round' + (cls ? ' ' + cls : ''), 'aria-hidden': 'true'}, name); + +const svg = (cls: string, markup: string) => { + const el = h('span', {class: cls}); + el.innerHTML = markup; + return el; +}; + +const aiMark = () => h('span', {class: 'tb-ai-mark'}, icon('auto_awesome')); + +const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +const wait = (el: T): T => { + el.classList.add('rq-wait'); + return el; +}; + +const come = (...els: HTMLElement[]) => els.forEach(el => { + el.classList.remove('rq-wait'); + el.classList.add('rq-in'); +}); + +type Step = [number, (still: boolean) => void | Promise]; + +function story(root: HTMLElement, ctx: SceneContext, steps: Step[]): void { + (async () => { + for (let n = 0; n < 40 && !root.isConnected; n++) { + await delay(50); + } + if (!root.isConnected) { + return; + } + for (const [ms, step] of steps) { + if (!ctx.still) { + await delay(ms); + } + if (!root.isConnected) { + return; + } + await step(ctx.still); + } + })(); +} + +async function typeText(el: HTMLElement, text: string, still: boolean): Promise { + if (still) { + el.textContent = text; + return; + } + for (let i = 1; i <= text.length && el.isConnected; i++) { + el.textContent = text.slice(0, i); + await delay(/[\s,.?]/.test(text[i - 1]) ? 70 + Math.random() * 70 : 24 + Math.random() * 40); + } +} + +const pointer = () => svg('rq-cursor', POINTER); + +async function pointAt(cursor: HTMLElement, el: HTMLElement, still: boolean): Promise { + if (still || !cursor.isConnected || !cursor.offsetParent || !el) { + return; + } + const host = cursor.offsetParent.getBoundingClientRect(); + const rect = el.getBoundingClientRect(); + cursor.classList.add('on'); + cursor.style.transform = `translate(${Math.round(rect.left - host.left + rect.width / 2)}px, ${Math.round(rect.top - host.top + rect.height / 2)}px)`; + await delay(560); + cursor.classList.add('press'); + el.classList.add('rq-pressed'); + await delay(170); + cursor.classList.remove('press'); + el.classList.remove('rq-pressed'); +} + +function composer(words: HTMLElement, o: { focus?: boolean; compact?: boolean; docked?: boolean; empty?: boolean } = {}): HTMLElement { + return q('rq-term' + (o.focus ? ' focus' : '') + (o.compact ? ' compact' : '') + (o.docked ? ' docked' : ''), + q('rq-term-in', icon('chevron_right', 'rq-pre'), h('span', {class: 'rq-term-words'}, words), + h('span', {class: 'rq-send' + (o.empty ? ' off' : '')}, icon('keyboard_return'))), + q('rq-term-foot', h('span', {class: 'rq-tool'}, icon('attach_file')), h('span', {class: 'rq-sp'}), + h('span', {class: 'rq-tool'}, icon('keyboard')))); +} + +const userMsg = (text: string | null, files?: HTMLElement[]) => + q('rq-user', files ? q('rq-files', files) : null, text ? q('rq-bubble', text) : null); + +const fileChip = (ic: string, name: string, meta: string) => + q('rq-file', h('span', {class: 'rq-file-ic', 'data-tone': 'rule'}, icon(ic)), h('span', null, h('b', null, name), h('small', null, meta))); + +function rec(kind: string, name: string, meta: string, o: { planned?: boolean; done?: boolean } = {}): HTMLElement { + const [ic, palette] = ENTITY[kind] ?? ENTITY.device; + return q('rq-rec' + (o.planned ? ' planned' : ''), + h('span', {class: 'rq-rec-tile', style: `background: var(--entity-${palette}-bg); color: var(--entity-${palette}-fg)`}, icon(ic)), + h('b', null, name), h('small', null, meta), o.done ? icon('check_circle', 'rq-rec-ok') : null); +} + +interface Ask { + text: string; + files?: () => HTMLElement[]; + reply: () => HTMLElement[]; +} + +function heroChat(ctx: SceneContext, asks: Ask[]): { words: HTMLElement; log: HTMLElement } { + const text = h('span', {class: 'rq-typed'}); + const caret = h('i', {class: 'rq-caret', 'aria-hidden': 'true'}); + const box = h('span', {class: 'rq-typing'}, text, caret); + const log = q('rq-log'); + const mine = (ask: Ask) => userMsg(ask.text, ask.files ? ask.files() : undefined); + (async () => { + for (let n = 0; n < 40 && !box.isConnected; n++) { + await delay(50); + } + if (!box.isConnected) { + return; + } + const send = box.closest('.rq-term')?.querySelector('.rq-send'); + if (ctx.still) { + caret.remove(); + text.className = 'rq-ph'; + text.textContent = ctx.t('tour.scene.cover.placeholder'); + send?.classList.add('off'); + log.classList.add('open'); + log.replaceChildren(mine(asks[1]), q('rq-agent', asks[1].reply())); + return; + } + const live = () => box.isConnected && !!box.closest('.iv-scene.on'); + for (let k = 0; live(); k = (k + 1) % asks.length) { + const ask = asks[k]; + text.textContent = ''; + box.classList.remove('sent'); + send?.classList.add('off'); + await delay(k ? 500 : 900); + send?.classList.remove('off'); + await typeText(text, ask.text, false); + await delay(550); + if (!live()) { + return; + } + send?.classList.add('press'); + await delay(140); + box.classList.add('sent'); + log.classList.add('out'); + await delay(210); + send?.classList.remove('press'); + send?.classList.add('off'); + text.textContent = ''; + box.classList.remove('sent'); + log.classList.add('open'); + log.replaceChildren(mine(ask)); + log.classList.remove('out'); + await delay(910); + if (!live()) { + return; + } + const agent = q('rq-agent'); + log.append(agent); + for (const node of ask.reply()) { + if (!live()) { + return; + } + agent.append(node); + await delay(550); + } + await delay(1500); + } + })(); + return {words: box, log}; +} + +function sceneCover(ctx: SceneContext, words: CoverWords): HTMLElement[] { + const t = (key: string) => ctx.t('tour.scene.cover.' + key); + const chat = heroChat(ctx, [ + {text: t('ask-1'), reply: () => [h('p', null, t('reply-1')), rec('device', t('record-1-name'), t('record-1-meta'))]}, + {text: t('ask-2'), reply: () => [h('p', null, t('reply-2')), rec('dashboard', t('record-2-name'), t('record-2-meta'), {done: true})]}, + {text: t('ask-3'), files: () => [fileChip('picture_as_pdf', t('file-3-name'), t('file-3-meta'))], reply: () => [h('p', null, t('reply-3'))]} + ]); + return [q('rq-hero', + h('span', {class: 'iv-version'}, icon('auto_awesome'), words.pill), + h('b', {class: 'rq-hero-t'}, h('span', null, words.news), h('span', {class: 'iv-grad'}, words.title)), + chat.log, composer(chat.words, {focus: true}))]; +} + +function sceneHome(ctx: SceneContext): HTMLElement[] { + const t = (key: string) => ctx.t('tour.scene.home.' + key); + const hour = new Date().getHours(); + const day = new Date().toLocaleDateString(ctx.locale, {weekday: 'long', day: 'numeric', month: 'long'}); + const pill = (...kids: Child[]) => wait(h('span', {class: 'rq-hpill'}, ...kids)); + const critical = pill(icon('warning'), t('critical')); + const quiet = pill(t('inactive')); + const placeholder = h('span', {class: 'rq-ph'}, t('placeholder')); + const text = h('span', {class: 'rq-typed'}); + const caret = h('i', {class: 'rq-caret', 'aria-hidden': 'true'}); + const box = h('span', {class: 'rq-typing'}, placeholder); + const row = q('rq-hrow', + q('rq-hfield', icon('chevron_right', 'rq-pre'), box, h('kbd', {class: 'rq-hkey'}, '/'), h('span', {class: 'rq-send'}, icon('keyboard_return'))), + h('span', {class: 'rq-hchats'}, icon('forum'), h('span', null, t('chats')), icon('chevron_right'))); + const chat = (title: string, meta: string) => h('span', {class: 'rq-hchat'}, h('i', null), h('b', null, title), h('small', null, meta)); + const waits = wait(q('rq-hwait', h('small', null, t('waiting')), q('rq-hchatrow', chat(t('chat-1'), '12m'), chat(t('chat-2'), '2h')))); + const card = (ic: string, name: string, count: string, widths: number[]) => q('rq-hcard', h('b', null, icon(ic), name, h('small', null, count)), + widths.map(width => h('i', {style: `width: ${width}%`}))); + const cards = wait(q('rq-hcards', card('warning', t('alarms'), '26', [92, 70, 84]), card('notifications', t('notifications'), '7', [88, 62, 80]))); + const page = q('rq-home', q('rq-hdate', day), + q('rq-hgreet', aiMark(), t(hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening')), + q('rq-hpills', critical, quiet), row, waits, cards); + story(page, ctx, [ + [600, () => come(critical)], + [160, () => come(quiet)], + [450, () => come(waits)], + [300, () => come(cards)], + [900, async still => { + if (still) { + return; + } + row.classList.add('typing'); + box.replaceChildren(text, caret); + await typeText(text, t('ask'), false); + }] + ]); + return [page]; +} + +function sceneAnyPage(ctx: SceneContext): HTMLElement[] { + const t = (key: string) => ctx.t('tour.scene.page.' + key); + const tile = (key: string, value: string, unit: string) => q('rq-tile', h('small', null, key), + h('b', null, h('span', {class: 'v'}, value), h('span', {class: 'u'}, unit))); + const prompt = (ic: string, text: string) => q('rq-prompt', icon(ic), h('span', null, text)); + const load = tile(t('load'), '4.1', 'kW'); + const alarm = q('rq-alarm', icon('warning'), t('alarm')); + const chart = svg('rq-chart', CHART); + const ask = prompt('help_outline', t('ask')); + const body = q('rq-cbody', q('rq-empty', aiMark(), h('b', null, t('title')), q('rq-prompts', ask, prompt('add_chart', t('prompt-2'))))); + const said = wait(h('p', null, t('answer'))); + const about = wait(rec('device', t('record-name'), t('record-meta'))); + const cursor = pointer(); + const win = q('iv-window rq-dock', + q('iv-sk-page', q('rq-ptop', h('b', null, t('page')), h('small', null, t('range'))), + q('rq-dash', q('iv-sk-row', load, tile(t('today'), '96', 'kWh')), chart, alarm)), + q('rq-companion', q('rq-chead', h('b', null, t('new-chat')), h('span', {class: 'rq-sp'}), icon('close')), body, + composer(h('span', {class: 'rq-ph'}, t('title')), {compact: true, empty: true, docked: true}))); + story(win, ctx, [ + [800, () => chart.classList.add('drawn')], + [640, () => { + load.classList.add('hot'); + load.querySelector('.v').textContent = '14.2'; + }], + [380, () => alarm.classList.add('on')], + [900, still => pointAt(cursor, ask, still)], + [0, () => ask.classList.add('picked')], + [260, () => { + cursor.classList.remove('on'); + body.classList.add('said'); + const mine = userMsg(t('ask')); + body.replaceChildren(mine, q('rq-agent', said, about)); + come(mine); + }], + [650, () => come(said)], + [550, () => come(about)] + ]); + return [win, cursor]; +} + +function scenePlan(ctx: SceneContext): HTMLElement[] { + const t = (key: string, params?: Record) => ctx.t('tour.scene.plan.' + key, params); + const rows = ([['dashboard', 'row-1', 'dashboard'], ['rule', 'row-2', 'alarm-rule'], ['notification', 'row-3', 'notification-rule']] as const) + .map(([kind, name, type]) => { + const el = wait(rec(kind, t(name), t('planned', {type: t(type)}), {planned: true})); + const made = () => { + el.classList.remove('planned'); + el.classList.add('made'); + el.querySelector('small').textContent = t('created', {type: t(type)}); + el.append(icon('check_circle', 'rq-rec-ok')); + }; + return {el, made}; + }); + const run = h('span', {class: 'rq-btn fill sm'}, icon('play_arrow'), t('run')); + const cursor = pointer(); + const mine = userMsg(t('request')); + const head = wait(q('rq-plan-h', h('b', null, t('plan')), h('small', null, t('steps')), h('span', {class: 'rq-sp'}), run)); + const win = q('iv-window rq-col', mine, q('rq-agent rq-plan', head, rows.map(row => row.el))); + story(win, ctx, [ + [1200, () => come(head)], + [180, () => come(rows[0].el)], + [180, () => come(rows[1].el)], + [180, () => come(rows[2].el)], + [900, still => pointAt(cursor, run, still)], + [0, () => { + run.classList.add('busy'); + run.replaceChildren(t('running')); + }], + [260, () => cursor.classList.remove('on')], + [420, () => rows[0].made()], + [520, () => rows[1].made()], + [520, () => { + rows[2].made(); + run.classList.remove('busy'); + run.classList.add('done'); + run.replaceChildren(icon('check'), t('done')); + }] + ]); + return [win, cursor]; +} + +function sceneAsk(ctx: SceneContext): HTMLElement[] { + const t = (key: string) => ctx.t('tour.scene.ask.' + key); + const chip = (text: string, on?: boolean) => h('span', {class: 'rq-chip' + (on ? ' on' : '')}, text); + const count = h('small', null, t('count-1')); + const next = h('span', {class: 'rq-btn fill'}, icon('arrow_forward'), t('next')); + const first = [chip(t('option-1-1')), chip(t('option-1-2')), chip(t('option-1-3')), chip(t('other'))]; + const said = q('rq-said'); + const ask = q('rq-ask-q', h('b', null, t('question-1')), h('span', null, t('why-1'))); + const chips = q('rq-chips', first); + const hint = h('p', {class: 'rq-ask-hint'}, t('hint-1')); + const cursor = pointer(); + const card = q('rq-review rq-ask', q('rq-rev-head', icon('help_outline'), t('needs-answer'), count), said, ask, chips, hint, + q('rq-actions', next, h('span', {class: 'rq-sp'}), h('span', {class: 'rq-btn text'}, t('skip')))); + story(card, ctx, [ + [1300, still => pointAt(cursor, first[1], still)], + [0, () => first[1].classList.add('on')], + [550, still => pointAt(cursor, next, still)], + [0, () => { + cursor.classList.remove('on'); + count.textContent = t('count-2'); + said.replaceChildren(icon('check'), h('span', null, t('said')), h('b', null, t('option-1-2'))); + said.classList.add('on'); + ask.replaceChildren(h('b', null, t('question-2')), h('span', null, t('why-2'))); + chips.replaceChildren(chip(t('option-2-1')), chip(t('option-2-2'), true), chip(t('option-2-3')), chip(t('other'))); + hint.textContent = t('hint-2'); + next.replaceChildren(icon('check'), t('done')); + come(ask, chips, hint); + }] + ]); + return [card, cursor]; +} + +function sceneFiles(ctx: SceneContext): HTMLElement[] { + const t = (key: string) => ctx.t('tour.scene.files.' + key); + const span = (cls: string, text: string) => h('span', {class: 'hl-' + cls}, text); + const code: Child[][] = [ + [span('flag', '#include'), ' ', span('str', '"SHT31.h"')], + [span('key', 'SHT31'), ' sensor;'], + [''], + [span('key', 'void'), ' ', span('cmd', 'loop'), '() {'], + [' ', span('key', 'float'), ' t = sensor.', span('cmd', 'getTemperature'), '();'], + [' ', span('cmd', 'publish'), '(', span('str', '"temperature"'), ', t);'], + [' ', span('cmd', 'delay'), '(', span('num', '30000'), ');'], + ['}'] + ]; + const lines = code.map((parts, k) => h('div', {class: 'rq-ln'}, h('i', null, String(k + 1)), h('span', null, ...parts))); + const tile = ([name, ic, palette]: string[]) => wait(q('rq-ft', + h('span', {class: 'rq-file-ic', style: `background: var(--entity-${palette}-bg); color: var(--entity-${palette}-fg)`}, icon(ic)), h('b', null, name))); + const ins = [['SHT31.pdf', 'picture_as_pdf', 'rule'], ['wiring.jpg', 'image', 'path'], ['stores.xlsx', 'table_chart', 'view'], + ['registers.csv', 'grid_on', 'view'], ['serial.log', 'subject', 'people']].map(tile); + const outs = [['sht31.ino', 'code', 'chain'], ['decoder.js', 'integration_instructions', 'chain'], ['config.json', 'data_object', 'device'], + ['compose.yml', 'tune', 'device'], ['setup.md', 'description', 'people']].map(tile); + const group = (label: string, tiles: HTMLElement[], cls: string) => q('rq-fgroup ' + cls, h('small', null, label), q('rq-ftiles', tiles)); + const cursor = pointer(); + const win = q('iv-window rq-files-w', + q('rq-fgrid', group(t('in'), ins, 'in'), group(t('out'), outs, 'out')), + q('rq-code', q('rq-code-head', icon('code'), h('b', null, 'sht31.ino'), h('span', {class: 'rq-sp'}), icon('search'), + h('span', {class: 'rq-code-edit'}, t('edit'))), q('rq-code-body', lines))); + story(win, ctx, [ + [450, async still => { + for (const el of [...ins, ...outs]) { + if (!el.isConnected) { + return; + } + come(el); + if (!still) { + await delay(55); + } + } + }], + [650, still => pointAt(cursor, outs[0], still)], + [0, () => outs[0].classList.add('on')], + [220, () => win.classList.add('open')], + [380, async still => { + cursor.classList.remove('on'); + for (const line of lines) { + if (!line.isConnected) { + return; + } + line.classList.add('w'); + if (!still) { + await delay(70); + } + } + }] + ]); + return [win, cursor]; +} + +export interface CoverWords { + pill: string; + news: string; + title: string; +} + +export const WELCOME_CARDS = 5; + +export function buildScene(n: number, ctx: SceneContext, words: CoverWords): HTMLElement { + const tone = TONES[n]; + const frame = h('div', { + class: 'iv-canvas iv-scene ' + (!n ? 'ai-field' : tone === 'sky' ? 'ai-field iv-sky' : 'iv-tone'), + 'data-level': n ? null : 'tile', + 'data-motion': n ? null : 'live', + 'data-tone': n && tone !== 'sky' ? tone : null, + 'data-scene': String(n), + 'aria-hidden': 'true' + }); + const parts = [() => sceneCover(ctx, words), () => sceneHome(ctx), () => sceneAnyPage(ctx), () => scenePlan(ctx), + () => sceneAsk(ctx), () => sceneFiles(ctx)][n](); + append(frame, parts); + return frame; +} diff --git a/ui-ngx/src/app/shared/components/markdown.component.ts b/ui-ngx/src/app/shared/components/markdown.component.ts index 70eb3dc78a..ddeacb71a2 100644 --- a/ui-ngx/src/app/shared/components/markdown.component.ts +++ b/ui-ngx/src/app/shared/components/markdown.component.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 { ChangeDetectorRef, Component, @@ -67,6 +68,10 @@ export class TbMarkdownComponent implements OnChanges { @coerceBoolean() usePlainMarkdown = false; + @Input() + @coerceBoolean() + highlight = true; + @Output() ready = new EventEmitter(); isMarkdownReady = false; @@ -113,7 +118,9 @@ export class TbMarkdownComponent implements OnChanges { const element: HTMLDivElement = this.renderer.createElement('div'); element.innerHTML = template; this.handlePlugins(element); - this.markdownService.highlight(element); + if (this.highlight) { + this.markdownService.highlight(element); + } const preElements = element.querySelectorAll('pre'); const matches = Array.from(template.matchAll(/)<\/pre>/g)); for (let i = 0; i < preElements.length; i++) { diff --git a/ui-ngx/src/app/shared/components/notification/notification.component.ts b/ui-ngx/src/app/shared/components/notification/notification.component.ts index 075f8530fc..e514054829 100644 --- a/ui-ngx/src/app/shared/components/notification/notification.component.ts +++ b/ui-ngx/src/app/shared/components/notification/notification.component.ts @@ -152,7 +152,8 @@ export class NotificationComponent implements OnInit { } else if (this.notification.type === NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST || this.notification.type === NotificationType.ADDON_ACCESS_REQUEST || this.notification.type === NotificationType.ADDON_ACCESS_ERROR || - this.notification.type === NotificationType.PLAN_UPGRADE_REQUEST) { + this.notification.type === NotificationType.PLAN_UPGRADE_REQUEST || + this.notification.type === NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST) { return {color: 'var(--tb-primary-500)'}; } return null; diff --git a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html index 4ca6d3f32e..1916551872 100644 --- a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html +++ b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html @@ -1,23 +1,22 @@
- @for (rule of passwordErrorRules; track $index) { - @if (!rule.policyProp || passwordPolicy[rule.policyProp] > 0) { -

- - {{ checkForError(rule.key) ? 'mdi:close' : 'mdi:check' }} - - {{ rule.translation | translate : passwordPolicy }} -

- } + @for (rule of applicableRules; track rule.key) { +

+ + {{ checkForError(rule.key) ? 'mdi:close' : 'mdi:check' }} + + {{ rule.translation | translate : passwordPolicy }} +

}
diff --git a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.ts b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.ts index 3a4e3bb7d4..12044e17bd 100644 --- a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.ts +++ b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.ts @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { Component, Input, ViewEncapsulation } from '@angular/core'; +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { Component, Input, OnChanges, ViewEncapsulation } from '@angular/core'; import { CdkOverlayOrigin, ConnectionPositionPair } from '@angular/cdk/overlay'; -import { passwordErrorRules } from '@shared/models/password.models'; +import { PasswordErrorRule, passwordErrorRules } from '@shared/models/password.models'; import { AbstractControl } from '@angular/forms'; import { UserPasswordPolicy } from '@shared/models/settings.models'; import { POSITION_MAP } from '@shared/models/overlay.models'; @@ -14,18 +15,22 @@ import { POSITION_MAP } from '@shared/models/overlay.models'; encapsulation: ViewEncapsulation.None, standalone: false }) -export class PasswordRequirementsTooltipComponent { +export class PasswordRequirementsTooltipComponent implements OnChanges { @Input() passwordControl: AbstractControl; @Input() passwordPolicy: UserPasswordPolicy; @Input() trigger: CdkOverlayOrigin; - passwordErrorRules = passwordErrorRules; + applicableRules: PasswordErrorRule[] = []; isTooltipOpen = false; overlayPositions: ConnectionPositionPair[] = [ {...POSITION_MAP.top, offsetY: -20} ]; + ngOnChanges(): void { + this.applicableRules = passwordErrorRules.filter(rule => rule.applies(this.passwordPolicy)); + } + checkForError(errorName: string): boolean { return this.passwordControl?.hasError(errorName) ?? false; } diff --git a/ui-ngx/src/app/shared/components/snack-bar-component.html b/ui-ngx/src/app/shared/components/snack-bar-component.html index bdb36678a4..2d6d1d6be8 100644 --- a/ui-ngx/src/app/shared/components/snack-bar-component.html +++ b/ui-ngx/src/app/shared/components/snack-bar-component.html @@ -1,7 +1,8 @@
@if (!notification.modern) {
- + } @else {
- + @if (notification.actionLabel) { + + } @else { + + }
}
diff --git a/ui-ngx/src/app/shared/components/toast.directive.ts b/ui-ngx/src/app/shared/components/toast.directive.ts index 34a0f616f0..f7072b3d8a 100644 --- a/ui-ngx/src/app/shared/components/toast.directive.ts +++ b/ui-ngx/src/app/shared/components/toast.directive.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 { AfterViewInit, ChangeDetectorRef, Component, ComponentRef, @@ -347,6 +348,7 @@ export class TbSnackBarComponent implements AfterViewInit, OnDestroy { action(event: MouseEvent): void { event.stopPropagation(); + this.notification.onAction?.(); if (this.snackBarRef) { this.snackBarRef.dismissWithAction(); } else { diff --git a/ui-ngx/src/app/shared/components/tour/tour-popup.component.scss b/ui-ngx/src/app/shared/components/tour/tour-popup.component.scss new file mode 100644 index 0000000000..7b7d78c6ca --- /dev/null +++ b/ui-ngx/src/app/shared/components/tour/tour-popup.component.scss @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.tb-popover.tb-tour-popover { + > .tb-popover-content > .tb-popover-arrow { + width: 12px; + height: 12px; + border: 0; + background: var(--tb-surface, #fff); + box-shadow: -1px -1px 0 rgba(0, 0, 0, 0.04); + } + + &.tb-popover-placement-bottom, &.tb-popover-placement-bottomLeft, &.tb-popover-placement-bottomRight { + padding-top: 14px; + + > .tb-popover-content > .tb-popover-arrow { + top: 8px; + } + } + + &.tb-popover-placement-top, &.tb-popover-placement-topLeft, &.tb-popover-placement-topRight { + padding-bottom: 14px; + + > .tb-popover-content > .tb-popover-arrow { + bottom: 8px; + box-shadow: 1px 1px 0 rgba(0, 0, 0, 0.04); + } + } + + &.tb-popover-placement-right, &.tb-popover-placement-rightTop, &.tb-popover-placement-rightBottom { + padding-left: 14px; + + > .tb-popover-content > .tb-popover-arrow { + left: 8px; + box-shadow: -1px 1px 0 rgba(0, 0, 0, 0.04); + } + } + + &.tb-popover-placement-left, &.tb-popover-placement-leftTop, &.tb-popover-placement-leftBottom { + padding-right: 14px; + + > .tb-popover-content > .tb-popover-arrow { + right: 8px; + box-shadow: 1px -1px 0 rgba(0, 0, 0, 0.04); + } + } + + .tb-popover-inner { + border-radius: 14px; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.04), 0 8px 24px rgba(16, 24, 40, 0.14), 0 24px 56px rgba(16, 24, 40, 0.16); + } + + .tb-popover-inner-content { + padding: 20px 48px 16px 24px; + + &:has(.tb-tour-popup.hint) { + padding: 14px 44px 12px 16px; + } + } +} + +.tb-tour-popup { + display: flex; + flex-direction: column; + gap: 8px; + width: min(288px, calc(100vw - 88px)); + + kbd { + display: inline-block; + min-width: 18px; + padding: 0 5px; + border-radius: 4px; + background: var(--chat-key, #f6f8f8); + box-shadow: inset 0 -1px 0 var(--tb-line, rgba(0, 0, 0, 0.12)); + font: 500 12px/18px var(--tb-font, Roboto, sans-serif); + text-align: center; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-tour-popup-title { + margin: 0; + font: 500 17px/24px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0; + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); + } + + .tb-tour-popup-x.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + position: absolute; + top: 12px; + right: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 4px; + border-radius: 50%; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + font-size: 24px; + width: 24px; + height: 24px; + } + + .mat-mdc-button-touch-target { + width: 32px; + height: 32px; + } + } + + .tb-tour-popup-text { + margin: 0; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + letter-spacing: 0; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + } + + .tb-tour-popup-actions { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 8px; + margin: 4px -28px 0 0; + + .mdc-button { + min-width: 0; + height: 36px; + padding: 0 14px; + border-radius: 8px; + } + } + + .tb-tour-popup-count { + margin-right: auto; + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + } + + .tb-tour-popup-go { + --mat-button-filled-container-color: var(--ai-action); + --mdc-filled-button-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); + --mdc-filled-button-label-text-color: var(--ai-on-action); + } + + .tb-tour-popup-skip { + --mat-button-text-label-text-color: var(--tb-ink); + --mdc-text-button-label-text-color: var(--tb-ink); + } + + &.hint { + width: min(260px, calc(100vw - 76px)); + + .tb-tour-popup-title { + display: flex; + align-items: center; + gap: 8px; + font: 500 15px/22px var(--tb-font, Roboto, sans-serif); + } + + .tb-tour-popup-mark { + --m: 28px; + } + + .tb-tour-popup-text { + margin-top: 4px; + text-wrap: pretty; + } + + .tb-tour-popup-actions { + margin: 12px -28px 0 0; + + .mdc-button { + height: 32px; + } + } + + .tb-tour-popup-x.mat-mdc-icon-button.mat-mdc-button-base { + top: 8px; + right: 8px; + } + } + + .tb-tour-popup-key { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + } +} diff --git a/ui-ngx/src/app/shared/components/tour/tour-popup.component.ts b/ui-ngx/src/app/shared/components/tour/tour-popup.component.ts new file mode 100644 index 0000000000..fbefc50c3d --- /dev/null +++ b/ui-ngx/src/app/shared/components/tour/tour-popup.component.ts @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angular/core'; + +@Component({ + selector: 'tb-tour-popup', + template: ` +
+

+ @if (hint) { + + } + {{ title }} +

+ @if (closable) { + + } +

+
+ @if (count) { + {{ count }} + } @else if (foot) { + + } + @if (skipLabel) { + + } + +
+
+ `, + styleUrls: ['./tour-popup.component.scss'], + encapsulation: ViewEncapsulation.None, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class TourPopupComponent { + + private static count = 0; + + readonly titleId = 'tb-tour-popup-title-' + (++TourPopupComponent.count); + + @Input() title: string; + + @Input() text: string; + + @Input() count: string | null = null; + + @Input() skipLabel: string | null = null; + + @Input() nextLabel: string; + + @Input() closable = true; + + @Input() hint = false; + + @Input() foot: string | null = null; + + @Output() next = new EventEmitter(); + + @Output() skip = new EventEmitter(); + + @Output() closed = new EventEmitter(); +} diff --git a/ui-ngx/src/app/shared/components/tour/tour-popup.service.ts b/ui-ngx/src/app/shared/components/tour/tour-popup.service.ts new file mode 100644 index 0000000000..3813ab68b2 --- /dev/null +++ b/ui-ngx/src/app/shared/components/tour/tour-popup.service.ts @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Injectable, Renderer2, ViewContainerRef } from '@angular/core'; +import { TbPopoverService } from '@shared/components/popover.service'; +import { TbPopoverComponent } from '@shared/components/popover.component'; +import { PopoverPreferredPlacement } from '@shared/components/popover.models'; +import { TourPopupComponent } from '@shared/components/tour/tour-popup.component'; + +export interface TourPopupConfig { + target: Element; + hostView: ViewContainerRef; + renderer: Renderer2; + placement: PopoverPreferredPlacement; + title: string; + text: string; + nextLabel: string; + count?: string | null; + skipLabel?: string | null; + closable?: boolean; + hint?: boolean; + foot?: string | null; + onNext?: () => void; + onSkip?: () => void; + onClose?: () => void; + onEscape?: () => void; + onHidden?: () => void; +} + +export const escapeTourText = (text: string): string => + text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +export interface TourPopupRef { + close(): void; +} + +@Injectable() +export class TourPopupService { + + constructor(private popoverService: TbPopoverService) {} + + show(config: TourPopupConfig): TourPopupRef { + let open = true; + const onKey = (event: KeyboardEvent) => { + if (event.key === 'Escape' && open) { + event.preventDefault(); + config.onEscape(); + } + }; + if (config.onEscape) { + document.addEventListener('keydown', onKey, true); + } + const popover: TbPopoverComponent = this.popoverService.displayPopover({ + trigger: config.target, + renderer: config.renderer, + componentType: TourPopupComponent, + hostView: config.hostView, + preferredPlacement: config.placement, + hideOnClickOutside: false, + showCloseButton: false, + context: { + title: config.title, + text: config.text, + nextLabel: config.nextLabel, + count: config.count ?? null, + skipLabel: config.skipLabel ?? null, + closable: config.closable ?? true, + hint: config.hint ?? false, + foot: config.foot ?? null + }, + visibleFn: visible => { + if (!visible) { + document.removeEventListener('keydown', onKey, true); + } + if (!visible && open) { + open = false; + config.onHidden?.(); + } + } + }); + popover.tbDestroy.subscribe(() => { + open = false; + document.removeEventListener('keydown', onKey, true); + }); + popover.tbOverlayClassName = 'tb-tour-popover'; + popover.updateStyles(); + const instance = popover.tbComponentRef.instance; + instance.next.subscribe(() => config.onNext?.()); + instance.skip.subscribe(() => config.onSkip?.()); + instance.closed.subscribe(() => config.onClose?.()); + return { + close: () => { + document.removeEventListener('keydown', onKey, true); + if (open) { + open = false; + popover.hide(); + } + } + }; + } +} diff --git a/ui-ngx/src/app/shared/models/ai-chat.models.ts b/ui-ngx/src/app/shared/models/ai-chat.models.ts index 4d4b19234e..dcbad75537 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -1,24 +1,76 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType } from '@shared/models/entity-type.models'; export interface ChatConfiguration { title: string; + autoApprove?: boolean; +} + +export type AnswerRating = 'UP' | 'DOWN' | 'NONE'; + +export type AnswerProblem = 'WRONG' | 'NOT_WHAT_I_ASKED' | 'WRONG_CHANGE' | 'TOO_SLOW' | 'OTHER'; + +export const ANSWER_PROBLEMS: AnswerProblem[] = ['WRONG', 'NOT_WHAT_I_ASKED', 'WRONG_CHANGE', 'TOO_SLOW', 'OTHER']; + +export interface AnswerFeedback { + answer: string; + rating?: AnswerRating; + problem?: AnswerProblem; + comment?: string; +} + +export interface ChatUpdate { + title?: string; + pinned?: boolean; + feedback?: AnswerFeedback; + autoApprove?: boolean; + fileEdit?: FileEdit; +} + +export interface FileEdit { + executionId: string; + content: string; } export interface ChatInfo extends ChatConfiguration { id: string; createdTime: number; + pinned?: boolean; + pinnedTime?: number; + prompt?: string; + status?: ChatStatus; + statusReason?: string; + updatedTime?: number; } +export type ChatStatus = 'RUNNING' | 'NEEDS_YOU' | 'NO_DATA' | 'FAILED'; + +export type ChatLevel = 'needs' | 'nodata' | 'running' | 'error'; + export interface BaseChatEvent { event: string; } +export interface AiReading { + key: string; + values: string[]; +} + +export interface AiEntityReference { + name: string; + entityType: string; + id: string; +} + export interface AssistantChatEvent extends BaseChatEvent { event: 'assistantMessage', data: { message: string; + references?: AiEntityReference[]; + severities?: string[]; + readings?: AiReading[]; } } @@ -31,11 +83,36 @@ export interface ToolExecutionRequested extends BaseChatToolEventData { needsApproval: boolean; destructive: boolean; message: string; + autoApproved?: boolean; title?: string; approveLabel?: string; denyLabel?: string; executing?: string; icon?: string; + review?: AiApprovalReview; + time?: number; + tool?: string; + arguments?: unknown; +} + +export type AiReviewFieldKind = 'FACT' | 'CHANGE' | 'UNCHANGED'; + +export interface AiReviewField { + kind: AiReviewFieldKind; + id?: string; + name?: string; + current?: string; + value?: string; +} + +export interface AiApprovalReview { + entityType: string; + name: string; + verb?: string; + detail?: string; + target?: string; + fields: AiReviewField[]; + change?: 'CREATE' | 'UPDATE' | 'DELETE'; } export interface AiAssistantPromptExample { @@ -47,11 +124,14 @@ export interface AiAssistantPanelConfig { view?: AiAssistantViewConfig; initialPromptPlaceholder: string; followUpPromptPlaceholder?: string; + title?: string; subTitle?: string; pageUrl?: string; showButton?: boolean; fill?: boolean; promptExamples?: AiAssistantPromptExample[]; + suggestion?: string; + welcomeKey?: string; } export interface BaseChatToolEventData { @@ -64,6 +144,8 @@ export interface ToolExecutionResult extends BaseChatToolEventData { message: string; icon?: string; affectedEntities?: Array; + reason?: string; + result?: string; } export interface ToolExecutionResultEvent extends BaseChatEvent { @@ -75,9 +157,16 @@ export interface ErrorEvent extends BaseChatEvent { event: 'error'; data: { message: string; + code?: 'CREDITS_USED_UP' | 'RATE_LIMITED'; }; } +export interface AiNotice { + kind: 'info' | 'warn' | 'block'; + icon: string; + text: string; +} + export interface ChatTitleGeneratedEvent extends BaseChatEvent { event: 'chatTitleGenerated'; data: { @@ -90,10 +179,54 @@ export interface TurnResumedEvent extends BaseChatEvent { data: Record; } +export interface TurnStoppedEvent extends BaseChatEvent { + event: 'turnStopped'; + data: Record; +} + +export interface ToolStarted extends BaseChatToolEventData { + tool: string; + arguments?: unknown; + startedAt?: number; +} + +export interface ToolStartedEvent extends BaseChatEvent { + event: 'toolStarted'; + data: ToolStarted; +} + +export interface ToolFinished extends BaseChatToolEventData { + status: 'SUCCESS' | 'FAILURE'; + durationMs: number; + result?: string; + affectedEntities?: Array; +} + +export interface ToolFinishedEvent extends BaseChatEvent { + event: 'toolFinished'; + data: ToolFinished; +} + +export type AiActionStatus = 'RUNNING' | 'SUCCESS' | 'FAILURE' | 'STOPPED'; + +export interface AiAction { + executionId: string; + tool: string; + arguments?: unknown; + status: AiActionStatus; + startedAt: number; + durationMs?: number; + result?: string; + affectedEntities?: Array; + edited?: boolean; + progress?: string; +} + export interface ApprovalResult { executionId: string; approved: boolean; autoApprove?: boolean; + reason?: string; } export enum ToolApprovalResult { @@ -102,43 +235,256 @@ export enum ToolApprovalResult { TIMEOUT = 'TIMEOUT' } -export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent - | TurnResumedEvent; +export interface MessageQueuedEvent extends BaseChatEvent { + event: 'messageQueued'; + data: Record; +} + +export interface AssistantDeltaChatEvent extends BaseChatEvent { + event: 'assistantDelta'; + data: { + text: string; + }; +} + +export interface ThinkingChatEvent extends BaseChatEvent { + event: 'thinking'; + data: {headline?: string; tool?: string; arguments?: unknown}; +} + +export interface LimitReachedChatEvent extends BaseChatEvent { + event: 'limitReached'; + data: AiPlatformLimit; +} + +export interface AiPlatformLimit { + errorCode: number; + message?: string; + entityType?: EntityType; + limit?: number; + subscriptionErrorCode?: 'LIMIT_REACHED' | 'FEATURE_DISABLED'; + subscriptionEntry?: string; + subscriptionValue?: number; +} + +export type ChatEvent = AssistantChatEvent | AssistantDeltaChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent + | TurnResumedEvent | TurnStoppedEvent | MessageQueuedEvent | ToolStartedEvent | ToolFinishedEvent | ThinkingChatEvent | LimitReachedChatEvent; export enum AiAssistantViewType { + PAGE = 'PAGE', + IOT_HUB = 'IOT_HUB', DASHBOARD = 'DASHBOARD', DASHBOARD_LIST = 'DASHBOARD_LIST', + DASHBOARD_GROUP_LIST = 'DASHBOARD_GROUP_LIST', + DASHBOARD_GROUP = 'DASHBOARD_GROUP', + REPORT_TEMPLATE_LIST = 'REPORT_TEMPLATE_LIST', + REPORT_TEMPLATE = 'REPORT_TEMPLATE', + SCHEDULED_REPORTS = 'SCHEDULED_REPORTS', + REPORTS = 'REPORTS', + WIDGET_TYPE_LIST = 'WIDGET_TYPE_LIST', + WIDGET_TYPE = 'WIDGET_TYPE', + NEW_WIDGET_TYPE = 'NEW_WIDGET_TYPE', + WIDGETS_BUNDLE_LIST = 'WIDGETS_BUNDLE_LIST', + WIDGETS_BUNDLE = 'WIDGETS_BUNDLE', + SCADA_SYMBOL_LIST = 'SCADA_SYMBOL_LIST', + SCADA_SYMBOL = 'SCADA_SYMBOL', ALARM_RULE = 'ALARM_RULE', ALARM_RULE_LIST = 'ALARM_RULE_LIST', ALARM_LIST = 'ALARM_LIST', + ALARM = 'ALARM', CALCULATED_FIELD = 'CALCULATED_FIELD', CALCULATED_FIELD_LIST = 'CALCULATED_FIELD_LIST', DEVICE = 'DEVICE', DEVICE_LIST = 'DEVICE_LIST', DEVICE_GROUP = 'DEVICE_GROUP', DEVICE_GROUP_LIST = 'DEVICE_GROUP_LIST', + ASSET_LIST = 'ASSET_LIST', + ASSET = 'ASSET', + ASSET_GROUP_LIST = 'ASSET_GROUP_LIST', + ASSET_GROUP = 'ASSET_GROUP', + ENTITY_VIEW_LIST = 'ENTITY_VIEW_LIST', + ENTITY_VIEW = 'ENTITY_VIEW', + ENTITY_VIEW_GROUP_LIST = 'ENTITY_VIEW_GROUP_LIST', + ENTITY_VIEW_GROUP = 'ENTITY_VIEW_GROUP', + DEVICE_PROFILE_LIST = 'DEVICE_PROFILE_LIST', + DEVICE_PROFILE = 'DEVICE_PROFILE', + ASSET_PROFILE_LIST = 'ASSET_PROFILE_LIST', + ASSET_PROFILE = 'ASSET_PROFILE', + CUSTOMER_LIST = 'CUSTOMER_LIST', + CUSTOMER = 'CUSTOMER', + CUSTOMER_GROUP_LIST = 'CUSTOMER_GROUP_LIST', + CUSTOMER_GROUP = 'CUSTOMER_GROUP', + USER_LIST = 'USER_LIST', + USER = 'USER', + USER_GROUP_LIST = 'USER_GROUP_LIST', + USER_GROUP = 'USER_GROUP', + ROLE_LIST = 'ROLE_LIST', + ROLE = 'ROLE', + RULE_CHAIN_LIST = 'RULE_CHAIN_LIST', + RULE_CHAIN = 'RULE_CHAIN', + INTEGRATION_LIST = 'INTEGRATION_LIST', + INTEGRATION = 'INTEGRATION', + CONVERTER_LIST = 'CONVERTER_LIST', + CONVERTER = 'CONVERTER', + EDGE_LIST = 'EDGE_LIST', + EDGE = 'EDGE', + EDGE_GROUP_LIST = 'EDGE_GROUP_LIST', + EDGE_GROUP = 'EDGE_GROUP', + EDGE_SCHEDULER = 'EDGE_SCHEDULER', + RULE_CHAIN_TEMPLATE_LIST = 'RULE_CHAIN_TEMPLATE_LIST', + RULE_CHAIN_TEMPLATE = 'RULE_CHAIN_TEMPLATE', + INTEGRATION_TEMPLATE_LIST = 'INTEGRATION_TEMPLATE_LIST', + INTEGRATION_TEMPLATE = 'INTEGRATION_TEMPLATE', + CONVERTER_TEMPLATE_LIST = 'CONVERTER_TEMPLATE_LIST', + CONVERTER_TEMPLATE = 'CONVERTER_TEMPLATE', + AGENT_LIST = 'AGENT_LIST', + AGENT = 'AGENT', + AGENT_GROUP_LIST = 'AGENT_GROUP_LIST', + AGENT_GROUP = 'AGENT_GROUP', + AGENT_APPLICATION_LIST = 'AGENT_APPLICATION_LIST', + AGENT_APPLICATION = 'AGENT_APPLICATION', + AGENT_EVENTS = 'AGENT_EVENTS', + AGENT_PROFILE_LIST = 'AGENT_PROFILE_LIST', + AGENT_PROFILE = 'AGENT_PROFILE', + AGENT_APP_PROFILE_LIST = 'AGENT_APP_PROFILE_LIST', + AGENT_APP_PROFILE = 'AGENT_APP_PROFILE', + AGENT_BULK_ACTION = 'AGENT_BULK_ACTION', NOTIFICATION_TEMPLATE_LIST = 'NOTIFICATION_TEMPLATE_LIST', NOTIFICATION_RULE_LIST = 'NOTIFICATION_RULE_LIST', NOTIFICATION_RECIPIENT_LIST = 'NOTIFICATION_RECIPIENT_LIST', SENT_NOTIFICATION_LIST = 'SENT_NOTIFICATION_LIST', - NOTIFICATION_INBOX = 'NOTIFICATION_INBOX' + NOTIFICATION_INBOX = 'NOTIFICATION_INBOX', + NOTIFICATION_TEMPLATE = 'NOTIFICATION_TEMPLATE', + NOTIFICATION_RULE = 'NOTIFICATION_RULE', + NOTIFICATION_RECIPIENT = 'NOTIFICATION_RECIPIENT', + CUSTOMER_HIERARCHY = 'CUSTOMER_HIERARCHY', + GATEWAYS = 'GATEWAYS', + OTA_UPDATES = 'OTA_UPDATES', + WHITE_LABELING = 'WHITE_LABELING', + LOGIN_WHITE_LABELING = 'LOGIN_WHITE_LABELING', + MAIL_TEMPLATES = 'MAIL_TEMPLATES', + CUSTOM_TRANSLATION = 'CUSTOM_TRANSLATION', + CUSTOM_MENU = 'CUSTOM_MENU', + IMAGES = 'IMAGES', + JAVASCRIPT_LIBRARY = 'JAVASCRIPT_LIBRARY', + RESOURCES_LIBRARY = 'RESOURCES_LIBRARY', + TWO_FACTOR_AUTH = 'TWO_FACTOR_AUTH', + OAUTH2_DOMAINS = 'OAUTH2_DOMAINS', + OAUTH2_CLIENTS = 'OAUTH2_CLIENTS', + SELF_REGISTRATION = 'SELF_REGISTRATION', + SECRETS = 'SECRETS', + AUDIT_LOGS = 'AUDIT_LOGS', + VERSION_CONTROL = 'VERSION_CONTROL', + TASK_MANAGER = 'TASK_MANAGER', + SCHEDULER = 'SCHEDULER', + HOME_SETTINGS = 'HOME_SETTINGS', + MAIL_SERVER_SETTINGS = 'MAIL_SERVER_SETTINGS', + NOTIFICATION_SETTINGS = 'NOTIFICATION_SETTINGS', + REPOSITORY_SETTINGS = 'REPOSITORY_SETTINGS', + AUTO_COMMIT_SETTINGS = 'AUTO_COMMIT_SETTINGS', + AI_MODELS = 'AI_MODELS', + API_USAGE = 'API_USAGE', + MOBILE_BUNDLES = 'MOBILE_BUNDLES', + MOBILE_APPS = 'MOBILE_APPS', + MOBILE_QR_CODE = 'MOBILE_QR_CODE', + ACCOUNT_PROFILE = 'ACCOUNT_PROFILE', + ACCOUNT_SECURITY = 'ACCOUNT_SECURITY', + ACCOUNT_NOTIFICATIONS = 'ACCOUNT_NOTIFICATIONS', + TRENDZ = 'TRENDZ' } +const AI_PAGE_VIEWS: Array<[string, AiAssistantViewType]> = [ + ['/iot-hub', AiAssistantViewType.IOT_HUB], + ['/customers/hierarchy', AiAssistantViewType.CUSTOMER_HIERARCHY], + ['/entities/gateways', AiAssistantViewType.GATEWAYS], + ['/features/otaUpdates', AiAssistantViewType.OTA_UPDATES], + ['/white-labeling/whiteLabel', AiAssistantViewType.WHITE_LABELING], + ['/white-labeling/loginWhiteLabel', AiAssistantViewType.LOGIN_WHITE_LABELING], + ['/white-labeling/mail-template', AiAssistantViewType.MAIL_TEMPLATES], + ['/white-labeling/customTranslation', AiAssistantViewType.CUSTOM_TRANSLATION], + ['/white-labeling/customMenu', AiAssistantViewType.CUSTOM_MENU], + ['/resources/images', AiAssistantViewType.IMAGES], + ['/resources/scada-symbols', AiAssistantViewType.SCADA_SYMBOL_LIST], + ['/resources/javascript-library', AiAssistantViewType.JAVASCRIPT_LIBRARY], + ['/resources/resources-library', AiAssistantViewType.RESOURCES_LIBRARY], + ['/security-settings/2fa', AiAssistantViewType.TWO_FACTOR_AUTH], + ['/security-settings/oauth2/domains', AiAssistantViewType.OAUTH2_DOMAINS], + ['/security-settings/oauth2/clients', AiAssistantViewType.OAUTH2_CLIENTS], + ['/security-settings/selfRegistration', AiAssistantViewType.SELF_REGISTRATION], + ['/security-settings/secrets', AiAssistantViewType.SECRETS], + ['/security-settings/auditLogs', AiAssistantViewType.AUDIT_LOGS], + ['/features/vc', AiAssistantViewType.VERSION_CONTROL], + ['/features/taskManager', AiAssistantViewType.TASK_MANAGER], + ['/features/scheduler', AiAssistantViewType.SCHEDULER], + ['/reporting/scheduling', AiAssistantViewType.SCHEDULED_REPORTS], + ['/reporting/reports', AiAssistantViewType.REPORTS], + ['/settings/home', AiAssistantViewType.HOME_SETTINGS], + ['/settings/outgoing-mail', AiAssistantViewType.MAIL_SERVER_SETTINGS], + ['/settings/notifications', AiAssistantViewType.NOTIFICATION_SETTINGS], + ['/settings/repository', AiAssistantViewType.REPOSITORY_SETTINGS], + ['/settings/auto-commit', AiAssistantViewType.AUTO_COMMIT_SETTINGS], + ['/settings/ai-models', AiAssistantViewType.AI_MODELS], + ['/usage', AiAssistantViewType.API_USAGE], + ['/mobile-center/bundles', AiAssistantViewType.MOBILE_BUNDLES], + ['/mobile-center/applications', AiAssistantViewType.MOBILE_APPS], + ['/mobile-center/qr-code-widget', AiAssistantViewType.MOBILE_QR_CODE], + ['/account/profile', AiAssistantViewType.ACCOUNT_PROFILE], + ['/account/security', AiAssistantViewType.ACCOUNT_SECURITY], + ['/account/notificationSettings', AiAssistantViewType.ACCOUNT_NOTIFICATIONS], + ['/analytics', AiAssistantViewType.TRENDZ] +]; + +const AI_PAGE_VIEW_PATTERNS: Array<[RegExp, AiAssistantViewType]> = [ + [/^\/resources\/scada-symbols\/(system|tenant)\/[^/]+$/, AiAssistantViewType.SCADA_SYMBOL], + [/^\/edgeManagement\/.*\/[0-9a-f-]{36}\/scheduler$/, AiAssistantViewType.EDGE_SCHEDULER], + [/^\/edgeManagement\/agents\/.*\/[0-9a-f-]{36}\/events$/, AiAssistantViewType.AGENT_EVENTS], + [/^\/edgeManagement\/profiles\/.*\/bulk\/[0-9a-f-]{36}$/, AiAssistantViewType.AGENT_BULK_ACTION] +]; + +const AI_TITLED_VIEWS = new Set([AiAssistantViewType.PAGE, ...AI_PAGE_VIEWS.map(([, type]) => type), + ...AI_PAGE_VIEW_PATTERNS.map(([, type]) => type)]); + +export const aiPageView = (path: string): AiAssistantViewType => + AI_PAGE_VIEW_PATTERNS.find(([pattern]) => pattern.test(path))?.[1] + ?? AI_PAGE_VIEWS.find(([prefix]) => path === prefix || path.startsWith(prefix + '/'))?.[1] + ?? AiAssistantViewType.PAGE; + +export const isAiTitledView = (type: string): boolean => AI_TITLED_VIEWS.has(type); + export interface AiChatView { type: AiAssistantViewType; entityId?: EntityId; dashboardState?: string; + title?: string; + path?: string; } export interface AiChatClientContext { view: AiChatView; timeZone?: string; + os?: string; +} + +export function aiClientOs(): string | undefined { + const nav = navigator as Navigator & {userAgentData?: {platform?: string}}; + const agent = `${nav.userAgentData?.platform ?? ''} ${navigator.userAgent}`; + return /Android/i.test(agent) ? 'android' : /iPhone|iPad|iPod/i.test(agent) ? 'ios' : /CrOS|Chrome OS/i.test(agent) ? 'chromeos' + : /Win/i.test(agent) ? 'windows' : /Mac/i.test(agent) ? 'macos' : /Linux|X11/i.test(agent) ? 'linux' : undefined; } export interface SendChatMessageRequest { message: string; clientContext?: AiChatClientContext; resources?: string[]; + secrets?: Record; + editorDraft?: unknown; +} + +export interface AiResourceFacts { + pages?: number; + rows?: number; + columns?: number; + lines?: number; } export interface AiResourceInfo { @@ -146,6 +492,7 @@ export interface AiResourceInfo { name: string; mediaType: string; size: number; + facts?: AiResourceFacts; } export interface AiResourceConfig { @@ -155,9 +502,39 @@ export interface AiResourceConfig { extensions: string[]; } +export interface AiLinesQuote { + name: string; + icon: string; + lang: string; + from: number; + to: number; + text: string; +} + export interface AiPromptMessage { message: string; resources: AiResourceInfo[]; + quote?: AiLinesQuote; + secrets?: Record; +} + +const QUOTE_PATTERN = /^About lines? (\d+)(?:–(\d+))? of (.+?):\n```([\w+-]*)\n([\s\S]*?)\n```\n*/; + +export function aiQuoteText(quote: AiLinesQuote, message: string): string { + const lines = quote.from === quote.to ? `line ${quote.from}` : `lines ${quote.from}–${quote.to}`; + return `About ${lines} of ${quote.name}:\n\`\`\`${quote.lang}\n${quote.text}\n\`\`\`\n\n${message}`; +} + +export function aiQuoteOf(content: string | undefined): {quote: Omit; message: string} | null { + const match = content ? QUOTE_PATTERN.exec(content) : null; + if (!match) { + return null; + } + const from = Number(match[1]); + return { + quote: {from, to: match[2] ? Number(match[2]) : from, name: match[3], lang: match[4], text: match[5]}, + message: content.slice(match[0].length) + }; } export const AI_IMAGE_MEDIA_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp']; diff --git a/ui-ngx/src/app/shared/models/custom-menu.models.ts b/ui-ngx/src/app/shared/models/custom-menu.models.ts index 78a133d2d3..3077a3478f 100644 --- a/ui-ngx/src/app/shared/models/custom-menu.models.ts +++ b/ui-ngx/src/app/shared/models/custom-menu.models.ts @@ -263,6 +263,32 @@ const afterLoadMenuItems = (items: MenuItem[]): MenuItem[] => { return items; }; +const LEGACY_MENU_IDS: Record = { + ai_solution_creator: 'ai_assistant' +}; + +export const withCurrentMenuIds = (config: CustomMenuConfig): CustomMenuConfig => { + if (!config?.items) { + return config; + } + const legacy = (items: MenuItem[]): boolean => items.some(item => !!LEGACY_MENU_IDS[item.id] || (!!item.pages && legacy(item.pages))); + if (!legacy(config.items)) { + return config; + } + const seen = new Set(); + const migrate = (items: MenuItem[]): MenuItem[] => items.flatMap(item => { + const id = LEGACY_MENU_IDS[item.id] ?? item.id; + if (id && seen.has(id)) { + return []; + } + if (id) { + seen.add(id); + } + return [{...item, ...(id ? {id: id as MenuId} : {}), ...(item.pages ? {pages: migrate(item.pages)} : {})}]; + }); + return {...config, items: migrate(config.items)}; +}; + const mergeFromDefaultMenu = (items: MenuItem[], defaultItems: MenuItem[]): MenuItem[] => { const menuItems: MenuItem[] = []; const defaultItemsMap = new Map(defaultItems.map(item => [item.id, item])); @@ -301,6 +327,7 @@ export const afterLoadCustomMenuConfig = (config: CustomMenuConfig, scope: CMSco if (!config?.items?.length) { return defaultMenuConfig; } else { + config = withCurrentMenuIds(config); config.items = afterLoadMenuItems(mergeFromDefaultMenu(config.items, defaultMenuConfig.items)); return config; } diff --git a/ui-ngx/src/app/shared/models/dashboard.models.ts b/ui-ngx/src/app/shared/models/dashboard.models.ts index 79637842d0..8fd8ba20c2 100644 --- a/ui-ngx/src/app/shared/models/dashboard.models.ts +++ b/ui-ngx/src/app/shared/models/dashboard.models.ts @@ -215,7 +215,6 @@ export type DashboardInfo = Dashboard & GroupEntityInfo; export interface HomeDashboard extends Dashboard { hideDashboardToolbar: boolean; - isSystemDashboard?: boolean; } export interface HomeDashboardInfo { diff --git a/ui-ngx/src/app/shared/models/device.models.ts b/ui-ngx/src/app/shared/models/device.models.ts index 57c38c6bd7..21561dcdd3 100644 --- a/ui-ngx/src/app/shared/models/device.models.ts +++ b/ui-ngx/src/app/shared/models/device.models.ts @@ -29,8 +29,6 @@ import type { Store } from '@ngrx/store'; import type { AppState } from '@core/core.state'; import type { TranslateService } from '@ngx-translate/core'; import type { UserPermissionsService } from '@core/http/user-permissions.service'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; -import { Operation, Resource } from '@shared/models/security.models'; import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; export enum DeviceProfileType { @@ -110,7 +108,6 @@ export const deviceTransportTypeTranslationMap = new Map( ] ); - export const deviceProvisionTypeTranslationMap = new Map( [ [DeviceProvisionType.DISABLED, 'device-profile.provision-strategy-disabled'], @@ -191,7 +188,6 @@ export const coapDeviceTypeTranslationMap = new Map( [ [ @@ -571,7 +567,6 @@ export const deviceProfileAlarmValidator = (control: AbstractControl): Validatio return {deviceProfileAlarm: true}; }; - export interface DeviceProfileData { configuration: DeviceProfileConfiguration; transportConfiguration: DeviceProfileTransportConfiguration; @@ -905,9 +900,7 @@ export function deviceAiAssistantConfig(store: Store, entityView?: AiAssistantViewType, listView: AiAssistantViewType = AiAssistantViewType.DEVICE_LIST, listEntityId?: EntityId): AiAssistantPanelConfig | null { - const hasPermission = getCurrentAuthState(store).aiEnabled && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - hasDevicePermission; + const hasPermission = userPermissionsService.isAiAvailable() && hasDevicePermission; if (!hasPermission) { return null; } @@ -918,6 +911,7 @@ export function deviceAiAssistantConfig(store: Store, entityView }, initialPromptPlaceholder: translate.instant('device.ai-assistant-initial-prompt-placeholder'), + suggestion: translate.instant('device.ai-assistant-suggestion'), promptExamples: [ { label: translate.instant('device.ai-assistant-example-connect-label'), diff --git a/ui-ngx/src/app/shared/models/notification.models.ts b/ui-ngx/src/app/shared/models/notification.models.ts index 9e183035d3..49ac213139 100644 --- a/ui-ngx/src/app/shared/models/notification.models.ts +++ b/ui-ngx/src/app/shared/models/notification.models.ts @@ -20,7 +20,6 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { TranslateService } from '@ngx-translate/core'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { Operation, Resource } from '@shared/models/security.models'; import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; import { Authority } from '@shared/models/authority.enum'; @@ -560,6 +559,7 @@ export enum NotificationType { ADDON_ACCESS_REQUEST = 'ADDON_ACCESS_REQUEST', ADDON_ACCESS_ERROR = 'ADDON_ACCESS_ERROR', PLAN_UPGRADE_REQUEST = 'PLAN_UPGRADE_REQUEST', + AI_CREDITS_LIMIT_INCREASE_REQUEST = 'AI_CREDITS_LIMIT_INCREASE_REQUEST', API_USAGE_LIMIT = 'API_USAGE_LIMIT', NEW_PLATFORM_VERSION = 'NEW_PLATFORM_VERSION', RULE_NODE = 'RULE_NODE', @@ -586,6 +586,7 @@ export const NotificationTypeIcons = new Map([ [NotificationType.ADDON_ACCESS_REQUEST, 'pending_actions'], [NotificationType.ADDON_ACCESS_ERROR, 'warning'], [NotificationType.PLAN_UPGRADE_REQUEST, 'mdi:file-cog'], + [NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, 'auto_awesome'], [NotificationType.API_USAGE_LIMIT, 'insert_chart'], [NotificationType.INTEGRATION_LIFECYCLE_EVENT, 'integration_instructions'], [NotificationType.TASK_PROCESSING_FAILURE, 'warning'], @@ -681,6 +682,12 @@ export const NotificationTemplateTypeTranslateMap = new Map { return type === NotificationType.USER_ACTIVATED || type === NotificationType.USER_REGISTERED || - type === NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST; + type === NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST || + type === NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST; } const sysAdminNotificationTypes: ReadonlySet = new Set([ @@ -812,6 +820,7 @@ const sysAdminNotificationTypes: ReadonlySet = new Set([ NotificationType.ADDON_ACCESS_REQUEST, NotificationType.ADDON_ACCESS_ERROR, NotificationType.PLAN_UPGRADE_REQUEST, + NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, NotificationType.API_USAGE_LIMIT, NotificationType.NEW_PLATFORM_VERSION, NotificationType.RATE_LIMITS, @@ -823,7 +832,8 @@ const adminRequestNotificationTypes: ReadonlySet = new Set([ NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST, NotificationType.ADDON_ACCESS_REQUEST, NotificationType.ADDON_ACCESS_ERROR, - NotificationType.PLAN_UPGRADE_REQUEST + NotificationType.PLAN_UPGRADE_REQUEST, + NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST ]); const edgeNotificationTypes: ReadonlySet = new Set([ @@ -844,7 +854,7 @@ export const isNotificationTypeReceivable = (type: NotificationType, authority: } break; default: - if (type === NotificationType.PLAN_UPGRADE_REQUEST) { + if (type === NotificationType.PLAN_UPGRADE_REQUEST || type === NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST) { return false; } } @@ -855,8 +865,7 @@ export function notificationAiAssistantConfig(store: Store, userPermissionsService: UserPermissionsService, translate: TranslateService, listView: AiAssistantViewType): AiAssistantPanelConfig | null { - const hasPermission = getCurrentAuthState(store).aiEnabled && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && + const hasPermission = userPermissionsService.isAiAvailable() && userPermissionsService.hasGenericPermission(Resource.NOTIFICATION, Operation.WRITE); if (!hasPermission) { return null; diff --git a/ui-ngx/src/app/shared/models/password.models.ts b/ui-ngx/src/app/shared/models/password.models.ts index 3d7119b362..11c501deba 100644 --- a/ui-ngx/src/app/shared/models/password.models.ts +++ b/ui-ngx/src/app/shared/models/password.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 { UserPasswordPolicy } from '@shared/models/settings.models'; import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { isEqual } from '@core/utils'; @@ -14,14 +15,20 @@ export enum TooltipPasswordErrorMessageKey { hasWhitespaces = 'security.password-requirement.password-should-not-contain-spaces' } -export const passwordErrorRules = [ - { key: 'minLength', policyProp: 'minimumLength', translation: TooltipPasswordErrorMessageKey.minLength }, - { key: 'notUpperCase', policyProp: 'minimumUppercaseLetters', translation: TooltipPasswordErrorMessageKey.notUpperCase }, - { key: 'notLowerCase', policyProp: 'minimumLowercaseLetters', translation: TooltipPasswordErrorMessageKey.notLowerCase }, - { key: 'notNumeric', policyProp: 'minimumDigits', translation: TooltipPasswordErrorMessageKey.notNumeric }, - { key: 'notSpecial', policyProp: 'minimumSpecialCharacters', translation: TooltipPasswordErrorMessageKey.notSpecial }, - { key: 'maxLength', policyProp: 'maximumLength', translation: TooltipPasswordErrorMessageKey.maxLength }, - { key: 'hasWhitespaces', policyProp: 'hasWhitespaces', translation: TooltipPasswordErrorMessageKey.hasWhitespaces }, +export interface PasswordErrorRule { + key: string; + translation: TooltipPasswordErrorMessageKey; + applies: (policy: UserPasswordPolicy) => boolean; +} + +export const passwordErrorRules: PasswordErrorRule[] = [ + { key: 'minLength', translation: TooltipPasswordErrorMessageKey.minLength, applies: policy => policy?.minimumLength > 0 }, + { key: 'notUpperCase', translation: TooltipPasswordErrorMessageKey.notUpperCase, applies: policy => policy?.minimumUppercaseLetters > 0 }, + { key: 'notLowerCase', translation: TooltipPasswordErrorMessageKey.notLowerCase, applies: policy => policy?.minimumLowercaseLetters > 0 }, + { key: 'notNumeric', translation: TooltipPasswordErrorMessageKey.notNumeric, applies: policy => policy?.minimumDigits > 0 }, + { key: 'notSpecial', translation: TooltipPasswordErrorMessageKey.notSpecial, applies: policy => policy?.minimumSpecialCharacters > 0 }, + { key: 'maxLength', translation: TooltipPasswordErrorMessageKey.maxLength, applies: policy => policy?.maximumLength > 0 }, + { key: 'hasWhitespaces', translation: TooltipPasswordErrorMessageKey.hasWhitespaces, applies: policy => policy?.allowWhitespaces === false }, ]; export const passwordsMatchValidator = (firstControlName: string, secondControlName: string): ValidatorFn =>{ diff --git a/ui-ngx/src/app/shared/models/settings.models.ts b/ui-ngx/src/app/shared/models/settings.models.ts index e4218859b4..b56b0a285e 100644 --- a/ui-ngx/src/app/shared/models/settings.models.ts +++ b/ui-ngx/src/app/shared/models/settings.models.ts @@ -549,10 +549,3 @@ export interface LicenseInfo { plan: string; } -export interface LicenseUsageInfo extends LicenseInfo { - devicesCount: number; - assetsCount: number; - edgesCount: number; - dashboardsCount: number; - integrationsCount: number; -} diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 5257dd27fb..e6ebc5f7ee 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -7,13 +7,26 @@ import { EntityId } from '@shared/models/id/entity-id'; import { BaseData } from '@shared/models/base-data'; import { CalculatedFieldType } from '@shared/models/calculated-field.models'; import { AlarmSeverity } from '@shared/models/alarm.models'; -import { ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AiAction, ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; + +export const NEW_SOLUTION_ID = 'new'; export interface SolutionInfo { id: string; + createdTime?: number; solutionTitle?: string; installed?: boolean; built?: boolean; + pinned?: boolean; + status?: 'RUNNING' | 'NEEDS_YOU' | 'FAILED'; + statusReason?: string; +} + +export type SolutionOperation = 'INITIAL_CONFIGURATION' | 'DASHBOARDS_CONFIGURATION' | 'CREATE' | 'INSTALL'; + +export interface SolutionEstimate { + credits: number; + seconds: number; } export interface SolutionCreatorInfo { @@ -22,11 +35,59 @@ export interface SolutionCreatorInfo { states: Record; data: SolutionData; metadata?: SolutionMetadata; + estimates?: Partial>; +} + +export interface SolutionProgressItem { + type: EntityType; + name?: string; + state: 'WAIT' | 'WORKING' | 'DONE'; + profile?: string; + customer?: string; +} + +export interface SolutionInstallProgress { + running: boolean; + phase?: string; + entityResults: Partial>; + stage?: 'CREATE' | 'INSTALL'; + items?: SolutionProgressItem[]; +} + +export interface SolutionUpdateRequest { + title?: string; + pinned?: boolean; + step?: SolutionStep; + feedback?: {answer: string; rating?: 'UP' | 'DOWN' | 'NONE'; problem?: string; comment?: string}; +} + +export interface AiQuestionOption { + label: string; + hint?: string; +} + +export interface AiQuestion { + id: string; + label?: string; + question: string; + why?: string; + options: AiQuestionOption[]; + recommended?: string | string[]; + multiple?: boolean; + secret?: boolean; + color?: boolean; +} + +export interface AiQuestionAnswer { + question: AiQuestion; + answer: string; + secret?: boolean; } export interface DashboardsOverview { name: string; assignedTo: string; + overview?: string; description: string; } @@ -35,6 +96,7 @@ export interface SolutionData { dashboardsOverview?: Array; dashboards?: Dashboard & {assignedTo: string}; solutionTitle?: string; + aiSolutionTitle?: string; solutionDescription?: string; entities?: any; } @@ -42,6 +104,8 @@ export interface SolutionData { export interface SolutionMetadata { installed: boolean; built: boolean; + builtTime?: number; + createDurationMs?: number; installResult?: SolutionInstallResult; } @@ -49,6 +113,8 @@ export interface SolutionInstallResult { mainDashboardId?: DashboardId; createdEntities: Array>; entityResults?: Record>; + installedTime?: number; + durationMs?: number; } export interface EntityResult { @@ -172,13 +238,42 @@ export interface SolutionStepState { skipInterviewAllowed?: boolean; } -export type ChatMessage = GeneralChatMessage | ApprovalChatMessage; +export type ChatMessage = GeneralChatMessage | ApprovalChatMessage | ActionChatMessage; + +export interface AiStartedFrom { + type: string; + entityId?: EntityId; + title?: string; + path?: string; +} export interface GeneralChatMessage { from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE'; content: string; - status?: 'INCOMPLETE'; + references?: Array<{name: string; entityType: string; id: string}>; + severities?: string[]; + readings?: Array<{key: string; values: string[]}>; + status?: 'INCOMPLETE' | 'STOPPED'; + streaming?: boolean; + rating?: 'UP' | 'DOWN'; + reported?: boolean; + startedFrom?: AiStartedFrom; resources?: AiResourceInfo[]; + time?: number; + questions?: AiQuestion[]; + answers?: AiQuestionAnswer[]; + done?: boolean; + lead?: string; + note?: string; + entities?: EntityId[]; + entitiesMeta?: string; + hint?: {lead: string; text: string}; + chips?: Array<{id: string; icon: string; label: string}>; +} + +export interface ActionChatMessage { + from: 'ACTION'; + data: AiAction; } export interface ApprovalChatMessage { diff --git a/ui-ngx/src/app/shared/models/user-settings.models.ts b/ui-ngx/src/app/shared/models/user-settings.models.ts index 9a18c98023..e9a4b9c1ef 100644 --- a/ui-ngx/src/app/shared/models/user-settings.models.ts +++ b/ui-ngx/src/app/shared/models/user-settings.models.ts @@ -11,9 +11,39 @@ export interface UserSettings { includeBundleWidgetsInExport?: boolean; includeResourcesInExportWidgetTypes?: boolean; includeResourcesInExportDashboard?: boolean; - isSolutionSidebarExpanded?: boolean; + aiTour?: AiTourSettings; + homeCards?: HomeCardsSettings; } +export enum AiTourStep { + WELCOME = 'welcome', + ASSISTANT_TOUR = 'assistantTour', + AI_BUTTON = 'aiButton', + HOME = 'home' +} + +export type AiTourSettings = Partial>; + +export enum HomeCardId { + IOT_HUB = 'iotHub', + ALARMS = 'alarms', + DASHBOARDS = 'dashboards', + DEVICES = 'devices', + ACTIVITY = 'activity', + GET_STARTED = 'getStarted', + NOTIFICATIONS = 'notifications', + QUICK_LINKS = 'quickLinks', + USAGE = 'usage', + MOBILE_APP = 'mobileApp', + PRODUCT_RELEASE = 'productRelease', + GET_STARTED_SYS_ADMIN = 'getStartedSysAdmin', + SYSTEM_STATUS = 'systemStatus', + LICENSE = 'license', + INSTALL_ITEMS = 'installItems' +} + +export type HomeCardsSettings = Partial>; + export const initialUserSettings: UserSettings = { openedMenuSections: [] }; @@ -36,13 +66,17 @@ export interface DocumentationLinks { links?: DocumentationLink[]; } +export const QUICK_WEB_LINK_PREFIX = 'url:'; + export interface QuickLinks { links?: string[]; + webLinks?: {[id: string]: DocumentationLink}; } export interface GettingStarted { maxSelectedIndex?: number; lastSelectedIndex?: number; + skipped?: string[]; } export interface AbstractUserDashboardInfo { diff --git a/ui-ngx/src/app/shared/shared.module.ts b/ui-ngx/src/app/shared/shared.module.ts index 8b720bdb49..21e9bbf13e 100644 --- a/ui-ngx/src/app/shared/shared.module.ts +++ b/ui-ngx/src/app/shared/shared.module.ts @@ -175,6 +175,8 @@ import { TbComponentOutletDirective } from '@shared/components/directives/compon import { HelpMarkdownComponent } from '@shared/components/help-markdown.component'; import { MarkedOptionsService } from '@shared/components/marked-options.service'; import { TbPopoverService } from '@shared/components/popover.service'; +import { TourPopupComponent } from '@shared/components/tour/tour-popup.component'; +import { TourPopupService } from '@shared/components/tour/tour-popup.service'; import { HELP_MARKDOWN_COMPONENT_TOKEN, SHARED_MODULE_TOKEN } from '@shared/components/tokens'; import { TbMarkdownComponent } from '@shared/components/markdown.component'; import { ProtobufContentComponent } from '@shared/components/protobuf-content.component'; @@ -327,6 +329,7 @@ export function MarkedOptionsFactory(markedOptionsService: MarkedOptionsService) { provide: SHARED_MODULE_TOKEN, useValue: SharedModule }, { provide: MatPaginatorIntl, useClass: CustomPaginatorIntl }, TbPopoverService, + TourPopupService, ImportExportService, { provide: MAT_SELECT_CONFIG, @@ -357,6 +360,7 @@ export function MarkedOptionsFactory(markedOptionsService: MarkedOptionsService) CountryData ], declarations: [ + TourPopupComponent, FooterComponent, LogoComponent, FooterFabButtonsComponent, @@ -624,6 +628,7 @@ export function MarkedOptionsFactory(markedOptionsService: MarkedOptionsService) DynamicMatDialogModule ], exports: [ + TourPopupComponent, FooterComponent, LogoComponent, FooterFabButtonsComponent, diff --git a/ui-ngx/src/assets/ai/agents/antigravity.svg b/ui-ngx/src/assets/ai/agents/antigravity.svg new file mode 100644 index 0000000000..8d79de680e --- /dev/null +++ b/ui-ngx/src/assets/ai/agents/antigravity.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ngx/src/assets/ai/agents/claude.svg b/ui-ngx/src/assets/ai/agents/claude.svg new file mode 100644 index 0000000000..988184cee8 --- /dev/null +++ b/ui-ngx/src/assets/ai/agents/claude.svg @@ -0,0 +1 @@ + diff --git a/ui-ngx/src/assets/dashboard/customer_user_home_page.json b/ui-ngx/src/assets/dashboard/customer_user_home_page.json deleted file mode 100644 index 00bc6304d3..0000000000 --- a/ui-ngx/src/assets/dashboard/customer_user_home_page.json +++ /dev/null @@ -1,492 +0,0 @@ -{ - "title": "Customer User Home Page", - "image": null, - "mobileHide": false, - "mobileOrder": null, - "configuration": { - "description": "", - "widgets": { - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "type": "static", - "sizeX": 7.5, - "sizeY": 3, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 2 - }, - "title": "Documentation", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false - }, - "row": 0, - "col": 0, - "id": "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4", - "typeFullFqn": "system.home_page_widgets.documentation_links" - }, - "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e": { - "type": "static", - "sizeX": 7.5, - "sizeY": 3, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 2 - }, - "title": "Quick links", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e", - "typeFullFqn": "system.home_page_widgets.quick_links" - }, - "6d6e2b1d-6ce7-4678-3745-c6b0897b2674": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": {}, - "title": "Dashboards", - "dropShadow": true, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "6d6e2b1d-6ce7-4678-3745-c6b0897b2674", - "typeFullFqn": "system.home_page_widgets.dashboards" - }, - "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "totalDevices", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": "42f42812-92fe-a13a-b0ba-c6e0dfab3584", - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "activeDevices", - "color": "#4caf50", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": "39d92c21-2426-7346-4484-452829146c33", - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "inactiveDevices", - "color": "#f44336", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n gap: 12px;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-item-cards {\n flex: 1;\n display: flex;\n flex-direction: row;\n gap: 12px;\n}\n\na.tb-item-card {\n flex: 1;\n display: flex;\n flex-direction: column;\n padding: 8px 12px;\n border: 1px solid;\n border-radius: 10px;\n margin-bottom: 12px;\n}\n\na.tb-item-card.tb-inactive {\n background: rgba(209, 39, 48, 0.04);\n border-color: rgba(209, 39, 48, 0.06);\n}\n\na.tb-item-card.tb-active {\n background: rgba(48, 86, 128, 0.04);\n border-color: rgba(48, 86, 128, 0.12);\n}\n\na.tb-item-card.tb-total {\n background: rgba(0, 0, 0, 0.01);\n border-color: rgba(0, 0, 0, 0.05);\n}\n\n.tb-item-title-container {\n display: grid;\n}\n\n.tb-item-title {\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis; \n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-item-title.tb-home-widget-link:after {\n position: absolute;\n right: 0;\n}\n\na.tb-item-card:hover .tb-item-title.tb-home-widget-link:after { \n color: rgba(0, 0, 0, 0.38);\n}\n\na.tb-item-card:hover {\n box-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08);\n}\n\n.tb-count-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n justify-content: center;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 24px;\n line-height: 36px;\n white-space: nowrap;\n color: rgba(0, 0, 0, 0.87);\n}\n\n@media screen and (max-width: 959px) {\n .tb-item-cards {\n flex-direction: column;\n }\n a.tb-item-card {\n margin-bottom: 0;\n }\n}\n\n@media screen and (max-width: 1279px) {\n a.tb-item-card {\n flex-direction: row;\n align-items: center;\n }\n .tb-item-title.tb-home-widget-link:after {\n position: relative;\n }\n .tb-count-container {\n align-items: flex-end;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-item-title {\n font-size: 11px;\n line-height: 16px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n a.tb-item-card {\n padding: 4px 8px;\n margin-bottom: 6px;\n }\n a.tb-item-card:hover {\n box-shadow: 0px 2px 5px rgba(23, 33, 90, 0.08);\n }\n}\n" - }, - "title": "Devices", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "" - }, - "row": 0, - "col": 0, - "id": "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6", - "typeFullFqn": "system.cards.markdown_card" - }, - "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "totalAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - } - }, - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "assignedToMeAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ], - "assignedToCurrentUser": true - } - }, - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "criticalAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ], - "severityList": [ - "CRITICAL" - ] - } - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n gap: 12px;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-item-cards {\n flex: 1;\n display: flex;\n flex-direction: row;\n gap: 12px;\n}\n\na.tb-item-card {\n flex: 1;\n display: flex;\n flex-direction: column;\n padding: 8px 12px;\n border: 1px solid;\n border-radius: 10px;\n margin-bottom: 12px;\n}\n\na.tb-item-card.tb-critical {\n background: rgba(209, 39, 48, 0.04);\n border-color: rgba(209, 39, 48, 0.06);\n}\n\na.tb-item-card.tb-assigned {\n background: rgba(48, 86, 128, 0.04);\n border-color: rgba(48, 86, 128, 0.12);\n}\n\na.tb-item-card.tb-total {\n background: rgba(0, 0, 0, 0.01);\n border-color: rgba(0, 0, 0, 0.05);\n}\n\n.tb-item-title-container {\n display: grid;\n}\n\n.tb-item-title {\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis; \n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-item-title.tb-home-widget-link:after {\n position: absolute;\n right: 0;\n}\n\na.tb-item-card:hover .tb-item-title.tb-home-widget-link:after { \n color: rgba(0, 0, 0, 0.38);\n}\n\na.tb-item-card:hover {\n box-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08);\n}\n\n.tb-count-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n justify-content: center;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 24px;\n line-height: 36px;\n white-space: nowrap;\n color: rgba(0, 0, 0, 0.87);\n}\n\na.tb-item-card.tb-critical .tb-count:after {\n content: \"warning\";\n display: inline-block;\n position: relative;\n font-family: 'Material Icons Round';\n color: #D12730;\n vertical-align: bottom;\n margin-left: 6px;\n}\n\n@media screen and (max-width: 959px) {\n .tb-item-cards {\n flex-direction: column;\n }\n a.tb-item-card {\n margin-bottom: 0;\n }\n}\n\n@media screen and (max-width: 1279px) {\n a.tb-item-card {\n flex-direction: row;\n align-items: center;\n }\n .tb-item-title.tb-home-widget-link:after {\n position: relative;\n }\n .tb-count-container {\n align-items: flex-end;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-item-title {\n font-size: 11px;\n line-height: 16px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n a.tb-item-card {\n padding: 4px 8px;\n margin-bottom: 6px;\n }\n a.tb-item-card:hover {\n box-shadow: 0px 2px 5px rgba(23, 33, 90, 0.08);\n }\n a.tb-item-card.tb-critical .tb-count:after {\n margin-left: 2px;\n }\n}\n" - }, - "title": "Alarms", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "" - }, - "row": 0, - "col": 0, - "id": "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb", - "typeFullFqn": "system.cards.markdown_card" - } - }, - "states": { - "default": { - "name": "Customer User Home Page", - "root": true, - "layouts": { - "main": { - "widgets": { - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "sizeX": 42, - "sizeY": 16, - "row": 42, - "col": 78, - "mobileHide": false, - "mobileOrder": 4, - "mobileHeight": 7 - }, - "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e": { - "sizeX": 42, - "sizeY": 16, - "row": 26, - "col": 78, - "mobileHide": false, - "mobileOrder": 3, - "mobileHeight": 7 - }, - "6d6e2b1d-6ce7-4678-3745-c6b0897b2674": { - "sizeX": 78, - "sizeY": 58, - "row": 0, - "col": 0, - "mobileOrder": 2, - "mobileHeight": 10 - }, - "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6": { - "sizeX": 42, - "sizeY": 13, - "row": 13, - "col": 78, - "mobileHeight": 9, - "mobileOrder": 1 - }, - "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb": { - "sizeX": 42, - "sizeY": 13, - "mobileHeight": 9, - "row": 0, - "col": 78, - "mobileOrder": 0 - } - }, - "gridSettings": { - "backgroundColor": "#eeeeee", - "columns": 120, - "margin": 12, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 20, - "outerMargin": true, - "layoutType": "default" - } - } - } - } - }, - "entityAliases": { - "a1ddb8fa-90ff-5598-e7f2-e254194d055d": { - "id": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "alias": "Devices", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "DEVICE" - } - }, - "d9229b29-3f46-de8d-7fe8-eb0c43c75079": { - "id": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "alias": "Api Usage State", - "filter": { - "type": "apiUsageState", - "resolveMultiple": true - } - } - }, - "filters": { - "42f42812-92fe-a13a-b0ba-c6e0dfab3584": { - "id": "42f42812-92fe-a13a-b0ba-c6e0dfab3584", - "filter": "Active Devices", - "keyFilters": [ - { - "key": { - "type": "SERVER_ATTRIBUTE", - "key": "active" - }, - "valueType": "BOOLEAN", - "predicates": [ - { - "keyFilterPredicate": { - "operation": "EQUAL", - "value": { - "defaultValue": true, - "dynamicValue": null - }, - "type": "BOOLEAN" - }, - "userInfo": { - "editable": true, - "label": "", - "autogeneratedLabel": true, - "order": 0 - } - } - ] - } - ], - "editable": false - }, - "39d92c21-2426-7346-4484-452829146c33": { - "id": "39d92c21-2426-7346-4484-452829146c33", - "filter": "Inactive Devices", - "keyFilters": [ - { - "key": { - "type": "SERVER_ATTRIBUTE", - "key": "active" - }, - "valueType": "BOOLEAN", - "predicates": [ - { - "keyFilterPredicate": { - "operation": "EQUAL", - "value": { - "defaultValue": false, - "dynamicValue": null - }, - "type": "BOOLEAN" - }, - "userInfo": { - "editable": true, - "label": "", - "autogeneratedLabel": true, - "order": 0 - } - } - ] - } - ], - "editable": false - } - }, - "timewindow": { - "selectedTab": 0, - "realtime": { - "realtimeType": 0, - "interval": 1000, - "timewindowMs": 60000 - }, - "aggregation": { - "type": "AVG" - } - }, - "settings": { - "stateControllerId": "entity", - "showTitle": false, - "showDashboardsSelect": true, - "showEntitiesSelect": true, - "showDashboardTimewindow": true, - "showDashboardExport": true, - "toolbarAlwaysOpen": true, - "titleColor": "rgba(0,0,0,0.870588)", - "showDashboardLogo": false, - "dashboardLogoUrl": null, - "hideToolbar": true, - "showFilters": true, - "showUpdateDashboardImage": true, - "dashboardCss": ".tb-widget-container > .tb-widget {\n border: 1px solid rgba(0, 0, 0, 0.05);\n box-shadow: 0px 5px 16px rgba(0, 0, 0, 0.04);\n border-radius: 12px;\n}\n\n.tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 16px !important;\n}\n\n.tb-card-title {\n display: grid;\n}\n\n.tb-home-widget-title {\n font-style: normal;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tb-home-widget-link {\n position: relative;\n border-bottom: none;\n}\n\n.tb-home-widget-link:hover {\n border-bottom: none;\n}\n\n.tb-home-widget-link:focus {\n border-bottom: none;\n}\n\n.tb-home-widget-link::after {\n content: 'arrow_forward';\n display: inline-block;\n transform: rotate(315deg);\n font-family: 'Material Icons';\n font-weight: normal;\n font-style: normal;\n font-size: 18px;\n color: rgba(0, 0, 0, 0.12);\n vertical-align: bottom;\n margin-left: 6px; \n}\n\n.tb-home-widget-link:hover::after {\n color: inherit;\n}\n\n.tb-home-widget-info-icon {\n color: rgba(0, 0, 0, 0.12);\n font-size: 16px;\n width: 16px;\n height: 16px;\n line-height: 15px;\n vertical-align: middle;\n}\n\n.tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n padding: 0;\n}\n\n.tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n cursor: pointer;\n user-select: none;\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1279px) {\n .tb-widget-container > .tb-widget {\n border-radius: 4px;\n }\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 2px !important;\n }\n .tb-hide-md {\n display: none;\n }\n}\n\n@media screen and (min-width: 1280px) and (max-width: 1819px) {\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 8px !important;\n }\n .tb-hide-lg {\n display: none;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-hide-md-lg {\n display: none;\n }\n\n .tb-home-widget-title {\n font-size: 12px;\n line-height: 16px;\n }\n \n .tb-widget-container > .tb-widget .tb-widget-title {\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 12px;\n line-height: 16px;\n min-height: 24px;\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 {\n width: 24px;\n height: 24px;\n line-height: 24px;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 .mat-icon {\n width: 18px;\n height: 18px;\n font-size: 18px;\n }\n \n .tb-widget-container > .tb-widget tb-legend {\n padding-bottom: 0 !important;\n }\n \n .tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n font-size: 11px;\n line-height: 16px;\n letter-spacing: 0.25px;\n }\n}\n\n@media screen and (max-width: 959px), screen and (min-width: 1820px) {\n .tb-hide-not-md-lg {\n display: none;\n }\n}\n" - } - }, - "name": "Customer User Home Page" -} \ No newline at end of file diff --git a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json b/ui-ngx/src/assets/dashboard/sys_admin_home_page.json deleted file mode 100644 index 59b57ee1fc..0000000000 --- a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json +++ /dev/null @@ -1,2682 +0,0 @@ -{ - "title": "System Administrator Home Page", - "image": null, - "mobileHide": false, - "mobileOrder": null, - "configuration": { - "description": "", - "widgets": { - "d70cc256-4c7b-ee06-9905-b8c5e546605f": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
{{ 'widgets.transport-messages.title' | translate }}\n info\n
\n
\n \n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n" - }, - "title": "Transport messages", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "d70cc256-4c7b-ee06-9905-b8c5e546605f", - "typeFullFqn": "system.cards.markdown_card" - }, - "4b5e47ed-c197-a937-d727-041ba8decec2": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entity", - "name": null, - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "filterId": null, - "dataKeys": [ - { - "name": "clusterMode", - "type": "timeseries", - "label": "clusterMode", - "color": "#2196f3", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": false, - "postFuncBody": "" - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#ffffff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextFunction": "let html = '
';\nlet clusterMode = data[0]['clusterMode'];\nif (clusterMode === 'true') {\n html += '';\n} else {\n html += '';\n}\nhtml += '
';\nreturn html;", - "applyDefaultMarkdownStyle": false - }, - "title": "System info", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": { - "border": "none", - "boxShadow": "none", - "padding": "0" - }, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "4b5e47ed-c197-a937-d727-041ba8decec2", - "typeFullFqn": "system.cards.markdown_card" - }, - "d2784f6c-0518-fd95-1d28-b21f70bdcb10": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
", - "applyDefaultMarkdownStyle": false - }, - "title": "Configured features", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "d2784f6c-0518-fd95-1d28-b21f70bdcb10", - "typeFullFqn": "system.cards.markdown_card" - }, - "66dcf1a2-9d83-6873-c693-d6a5d989b3f8": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
", - "applyDefaultMarkdownStyle": false - }, - "title": "Version", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "66dcf1a2-9d83-6873-c693-d6a5d989b3f8", - "typeFullFqn": "system.cards.markdown_card" - }, - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "type": "static", - "sizeX": 7.5, - "sizeY": 3, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 3 - }, - "title": "Documentation", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false - }, - "row": 0, - "col": 0, - "id": "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4", - "typeFullFqn": "system.home_page_widgets.documentation_links" - }, - "a17ef013-1fcf-53e1-a9ac-770668dcaed0": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
", - "applyDefaultMarkdownStyle": false - }, - "title": "License info", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "a17ef013-1fcf-53e1-a9ac-770668dcaed0", - "typeFullFqn": "system.cards.markdown_card" - }, - "025868f4-ca7a-8f92-6025-8815a55541b8": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "ae870700-071f-b3bc-406c-16ba554c5a55", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "tenantsCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
\n \n add\n \n
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n white-space: nowrap;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-small-button-container {\n display: flex;\n flex-direction: column;\n justify-content: center;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 28px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}\n" - }, - "title": "Tenants", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "025868f4-ca7a-8f92-6025-8815a55541b8", - "typeFullFqn": "system.cards.markdown_card" - }, - "bcb4bd75-2999-648d-d802-fda90ada07ab": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "ca4d90e4-f9ae-6fca-6b09-85815a48d52b", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "tenantProfilesCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "\n", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-small-button-container {\n display: flex;\n flex-direction: column;\n justify-content: center;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 28px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}\n" - }, - "title": "Tenant Profiles", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "bcb4bd75-2999-648d-d802-fda90ada07ab", - "typeFullFqn": "system.cards.markdown_card" - }, - "5fb122d1-a399-ce8e-8bb8-d2710dd98c18": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "devicesCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
{{ 'device.devices' | translate }}
\n
\n
${devicesCount:0}
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}" - }, - "title": "Devices", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "5fb122d1-a399-ce8e-8bb8-d2710dd98c18", - "typeFullFqn": "system.cards.markdown_card" - }, - "5c3d9d58-dd36-1ff3-b304-87345c6fefd2": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "619cdf00-a042-3b55-124e-194c1b28c236", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "assetsCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
{{ 'asset.assets' | translate }}
\n
\n
${assetsCount:0}
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}" - }, - "title": "Assets", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "5c3d9d58-dd36-1ff3-b304-87345c6fefd2", - "typeFullFqn": "system.cards.markdown_card" - }, - "d8da4ee1-cd83-5387-2fc7-a2e3f4b6422c": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "1d97ff7f-8b42-5882-f87b-16f3d0dee4f2", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "usersCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
{{ 'user.users' | translate }}
\n
\n
${usersCount:0}
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}\n" - }, - "title": "Users", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "d8da4ee1-cd83-5387-2fc7-a2e3f4b6422c", - "typeFullFqn": "system.cards.markdown_card" - }, - "6ade2191-7c3d-244e-43ff-51feaa9d1735": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "0dd2b154-59f4-0f97-da1a-d85f5b5cfe31", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "customersCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
{{ 'customer.customers' | translate }}
\n
\n
${customersCount:0}
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-count {\n font-size: 18px;\n line-height: 24px;\n }\n}" - }, - "title": "Customers", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "6ade2191-7c3d-244e-43ff-51feaa9d1735", - "typeFullFqn": "system.cards.markdown_card" - }, - "ba2b1a0c-c125-b246-d75b-8bbfe726c9e7": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "ae870700-071f-b3bc-406c-16ba554c5a55", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "tenantsCount", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "ca4d90e4-f9ae-6fca-6b09-85815a48d52b", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "tenantProfilesCount", - "color": "#4caf50", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "devicesCount", - "color": "#f44336", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "619cdf00-a042-3b55-124e-194c1b28c236", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "assetsCount", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "1d97ff7f-8b42-5882-f87b-16f3d0dee4f2", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "usersCount", - "color": "#607d8b", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "0dd2b154-59f4-0f97-da1a-d85f5b5cfe31", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "customersCount", - "color": "#9c27b0", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
\n
\n
${devicesCount:0}
\n
{{ 'device.devices' | translate }}
\n
\n
\n
${assetsCount:0}
\n
{{ 'asset.assets' | translate }}
\n
\n
\n
${usersCount:0}
\n
{{ 'user.users' | translate }}
\n
\n
\n
${customersCount:0}
\n
{{ 'customer.customers' | translate }}
\n
\n
\n
\n", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n justify-content: flex-start;\n align-items: stretch;\n}\n\n.tb-card-section {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: space-evenly;\n align-items: stretch;\n}\n\n.tb-card-section.left {\n border-right: solid 1px rgba(0, 0, 0, 0.12);\n}\n\n.tb-card-section.right .tb-entity-section {\n padding-left: 40px;\n}\n\n.tb-card-section.right .tb-count {\n min-width: 24px;\n text-align: right;\n}\n\n.tb-button-section {\n display: flex;\n padding-right: 40px;\n flex-direction: row;\n justify-content: flex-end;\n align-items: center;\n}\n\n.tb-entity-section {\n display: flex;\n flex-direction: row;\n justify-content: flex-start;\n align-items: center;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 600;\n font-size: 20px;\n line-height: 24px;\n margin-right: 12px;\n}\n\n.tb-entity-title {\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n" - }, - "title": "Entities info mobile card", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "ba2b1a0c-c125-b246-d75b-8bbfe726c9e7", - "typeFullFqn": "system.cards.markdown_card" - }, - "3f10c1f8-a990-b0e8-bbfe-f4f92b0901c2": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "rgba(0,0,0,0)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n \n \n \n
", - "applyDefaultMarkdownStyle": false - }, - "title": "Entities info cards", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": { - "border": "none", - "boxShadow": "none", - "padding": "0" - }, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "3f10c1f8-a990-b0e8-bbfe-f4f92b0901c2", - "typeFullFqn": "system.cards.markdown_card" - }, - "182cab27-6f94-7b5e-fc87-6cbdced3e24f": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entity", - "name": null, - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "filterId": null, - "dataKeys": [ - { - "name": "cpuUsage", - "type": "timeseries", - "label": "cpuUsage", - "color": "#2196f3", - "settings": {} - }, - { - "name": "cpuCount", - "type": "timeseries", - "label": "cpuCount", - "color": "#4caf50", - "settings": {} - }, - { - "name": "cpuUsage", - "type": "timeseries", - "label": "status", - "color": "#f44336", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "cpuUsage", - "type": "timeseries", - "label": "statusTooltip", - "color": "#ffc107", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.cpu-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.cpu-warning-text\\' | translate }}';\n}\nreturn text;\n" - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
widgets.system-info.cpu
\n
\n
\n
\n ${cpuUsage:0}%\n | ${cpuCount:0} cores\n
\n
", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-start;\n}\n\n.tb-card-title {\n width: 100%;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-status {\n width: 24px;\n height: 24px;\n position: relative;\n}\n\n.tb-status.status-ok {\n background: transparent;\n border-radius: 4px;\n}\n\n.tb-status.status-ok:before {\n content: \"\";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n border-radius: 4px;\n background: var(--tb-primary-500);\n opacity: 0.04;\n}\n\n.tb-status:after {\n position: absolute;\n top: 2px;\n left: 2px;\n font-family: 'Material Icons Round';\n font-size: 20px;\n line-height: 1;\n}\n\n.tb-status.status-ok:after {\n content: \"check\";\n color: #198038;\n font-weight: 600;\n}\n\n.tb-status.status-warn:after {\n content: \"warning\";\n color: #FAA405;\n}\n\n.tb-status.status-critical:after {\n content: \"warning\";\n color: #D12730;\n}\n\n.tb-value-container {\n user-select: none;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n.tb-total {\n padding-left: 4px;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-status {\n width: 18px;\n height: 18px;\n }\n .tb-status:after {\n font-size: 14px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n .tb-total {\n font-size: 11px;\n line-height: 16px;\n }\n}" - }, - "title": "CPU", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": ".tb-widget-container {\n display: block;\n height: 100%;\n}\n\n@media screen and (min-width: 960px) {\n .tb-widget-container {\n margin-right: 6px;\n }\n}\n\n@media screen and (max-width: 959px) {\n .tb-widget-container {\n height: calc(100% - 12px);\n margin-bottom: 12px;\n }\n}", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "182cab27-6f94-7b5e-fc87-6cbdced3e24f", - "typeFullFqn": "system.cards.markdown_card" - }, - "329a0477-ab07-efa1-f48f-6a3b5b7025a4": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entity", - "name": null, - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "filterId": null, - "dataKeys": [ - { - "name": "memoryUsage", - "type": "timeseries", - "label": "memoryUsage", - "color": "#2196f3", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - }, - { - "name": "totalMemory", - "type": "timeseries", - "label": "totalMemory", - "color": "#4caf50", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "return value / 1073741824;" - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "status", - "color": "#f44336", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "statusTooltip", - "color": "#ffc107", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.ram-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.ram-warning-text\\' | translate }}';\n}\nreturn text;\n" - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextFunction": "const memoryUsage = data[0]['memoryUsage'];\nconst totalMemory = data[0]['totalMemory'];\nconst usedMemory = (totalMemory * (memoryUsage / 100)).toFixed(0);\n\n\nreturn '
' +\n '
' +\n '
widgets.system-info.ram
' +\n '
' +\n '
' +\n '
' +\n '${memoryUsage:0}%' +\n '| ${totalMemory:0} Gb' +\n '
' +\n '
';", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-start;\n}\n\n.tb-card-title {\n width: 100%;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-status {\n width: 24px;\n height: 24px;\n position: relative;\n}\n\n.tb-status.status-ok {\n background: transparent;\n border-radius: 4px;\n}\n\n.tb-status.status-ok:before {\n content: \"\";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n border-radius: 4px;\n background: var(--tb-primary-500);\n opacity: 0.04;\n}\n\n.tb-status:after {\n position: absolute;\n top: 2px;\n left: 2px;\n font-family: 'Material Icons Round';\n font-size: 20px;\n line-height: 1;\n}\n\n.tb-status.status-ok:after {\n content: \"check\";\n color: #198038;\n font-weight: 600;\n}\n\n.tb-status.status-warn:after {\n content: \"warning\";\n color: #FAA405;\n}\n\n.tb-status.status-critical:after {\n content: \"warning\";\n color: #D12730;\n}\n\n.tb-value-container {\n user-select: none;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n.tb-total {\n padding-left: 4px;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-status {\n width: 18px;\n height: 18px;\n }\n .tb-status:after {\n font-size: 14px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n .tb-total {\n font-size: 11px;\n line-height: 16px;\n }\n}" - }, - "title": "RAM", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": ".tb-widget-container {\n display: block;\n height: 100%;\n}\n\n@media screen and (min-width: 960px) {\n .tb-widget-container {\n margin-right: 6px;\n margin-left: 6px;\n }\n}\n\n@media screen and (max-width: 959px) {\n .tb-widget-container {\n height: calc(100% - 12px);\n margin-bottom: 12px;\n }\n}", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "329a0477-ab07-efa1-f48f-6a3b5b7025a4", - "typeFullFqn": "system.cards.markdown_card" - }, - "85cbbe9b-d6a1-fe82-b600-99ced2dd441f": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entity", - "name": null, - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "filterId": null, - "dataKeys": [ - { - "name": "discUsage", - "type": "timeseries", - "label": "discUsage", - "color": "#2196f3", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - }, - { - "name": "totalDiscSpace", - "type": "timeseries", - "label": "totalDiscSpace", - "color": "#4caf50", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "return value / 1073741824;" - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "status", - "color": "#f44336", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "statusTooltip", - "color": "#ffc107", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.disk-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.disk-warning-text\\' | translate }}';\n}\nreturn text;" - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextFunction": "const discUsage = data[0]['discUsage'];\nconst totalDiscSpace = data[0]['totalDiscSpace'];\nconst usedDisc = (totalDiscSpace * (discUsage / 100)).toFixed(0);\n\n\nreturn '
' +\n '
' +\n '
widgets.system-info.disk
' +\n '
' +\n '
' +\n '
' +\n '${discUsage:0}%' +\n '| ${totalDiscSpace:0} Gb' +\n '
' +\n '
';", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-start;\n}\n\n.tb-card-title {\n width: 100%;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-status {\n width: 24px;\n height: 24px;\n position: relative;\n}\n\n.tb-status.status-ok {\n background: transparent;\n border-radius: 4px;\n}\n\n.tb-status.status-ok:before {\n content: \"\";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n border-radius: 4px;\n background: var(--tb-primary-500);\n opacity: 0.04;\n}\n\n.tb-status:after {\n position: absolute;\n top: 2px;\n left: 2px;\n font-family: 'Material Icons Round';\n font-size: 20px;\n line-height: 1;\n}\n\n.tb-status.status-ok:after {\n content: \"check\";\n color: #198038;\n font-weight: 600;\n}\n\n.tb-status.status-warn:after {\n content: \"warning\";\n color: #FAA405;\n}\n\n.tb-status.status-critical:after {\n content: \"warning\";\n color: #D12730;\n}\n\n.tb-value-container {\n user-select: none;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 26px;\n line-height: 36px;\n}\n\n.tb-total {\n padding-left: 4px;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-status {\n width: 18px;\n height: 18px;\n }\n .tb-status:after {\n font-size: 14px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n .tb-total {\n font-size: 11px;\n line-height: 16px;\n }\n}" - }, - "title": "Disk", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": ".tb-widget-container {\n display: block;\n height: 100%;\n}\n\n@media screen and (min-width: 960px) {\n .tb-widget-container {\n margin-left: 6px;\n }\n}\n\n@media screen and (max-width: 959px) {\n .tb-widget-container {\n height: calc(100% - 12px);\n margin-bottom: 12px;\n }\n}", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "85cbbe9b-d6a1-fe82-b600-99ced2dd441f", - "typeFullFqn": "system.cards.markdown_card" - }, - "bcde0229-2463-00ee-b602-6f8d9280228d": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entity", - "name": null, - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "filterId": null, - "dataKeys": [ - { - "name": "cpuUsage", - "type": "timeseries", - "label": "cpuUsage", - "color": "#2196f3", - "settings": {} - }, - { - "name": "cpuCount", - "type": "timeseries", - "label": "cpuCount", - "color": "#4caf50", - "settings": {} - }, - { - "name": "cpuUsage", - "type": "timeseries", - "label": "cpuStatus", - "color": "#f44336", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "cpuUsage", - "type": "timeseries", - "label": "cpuStatusTooltip", - "color": "#ffc107", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.cpu-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.cpu-warning-text\\' | translate }}';\n}\nreturn text;\n" - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "memoryUsage", - "color": "#607d8b", - "settings": {} - }, - { - "name": "totalMemory", - "type": "timeseries", - "label": "totalMemory", - "color": "#9c27b0", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "return value / 1073741824;" - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "memoryStatus", - "color": "#8bc34a", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "memoryStatusTooltip", - "color": "#3f51b5", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.ram-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.ram-warning-text\\' | translate }}';\n}\nreturn text;" - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "discUsage", - "color": "#e91e63", - "settings": {} - }, - { - "name": "totalDiscSpace", - "type": "timeseries", - "label": "totalDiscSpace", - "color": "#ffeb3b", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "return value / 1073741824;" - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "discStatus", - "color": "#03a9f4", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var status = 'status-ok';\nif (value > 85) {\n status = 'status-critical';\n} else if (value > 75) {\n status = 'status-warn';\n}\nreturn status;" - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "discStatusTooltip", - "color": "#ff9800", - "settings": {}, - "aggregationType": "NONE", - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": true, - "postFuncBody": "var text = '';\nif (value > 85) {\n text = '{{ \\'widgets.system-info.disk-critical-text\\' | translate }}';\n} else if (value > 75) {\n text = '{{ \\'widgets.system-info.disk-warning-text\\' | translate }}';\n}\nreturn text;" - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextFunction": "const memoryUsage = data[0]['memoryUsage'];\nconst totalMemory = data[0]['totalMemory'];\nconst usedMemory = (totalMemory * (memoryUsage / 100)).toFixed(0);\n\nconst discUsage = data[0]['discUsage'];\nconst totalDiscSpace = data[0]['totalDiscSpace'];\nconst usedDisc = (totalDiscSpace * (discUsage / 100)).toFixed(0);\n\n\nreturn '
' +\n '
' +\n '
' +\n '
widgets.system-info.cpu
' +\n '
' +\n '
' +\n '
' +\n '${cpuUsage:0}%' +\n '| ${cpuCount:0} cores' +\n '
' +\n '
' +\n '
' +\n '
' +\n '
widgets.system-info.ram
' +\n '
' +\n '
' +\n '
' +\n '${memoryUsage:0}%' +\n '| ${totalMemory:0} Gb' +\n '
' +\n '
' +\n '
' +\n '
' +\n '
widgets.system-info.disk
' +\n '
' +\n '
' +\n '
' +\n '${discUsage:0}%' +\n '| ${totalDiscSpace:0} Gb' +\n '
' +\n '
' +\n '
';", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n justify-content: flex-start;\n align-items: stretch;\n}\n\n.tb-card-section {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n align-items: flex-start;\n}\n\n.tb-card-section.left {\n padding-right: 12px;\n border-right: solid 1px rgba(0, 0, 0, 0.12);\n}\n\n.tb-card-section.center {\n padding-left: 12px;\n padding-right: 12px;\n}\n\n.tb-card-section.right {\n padding-left: 12px;\n border-left: solid 1px rgba(0, 0, 0, 0.12);\n}\n\n.tb-card-title {\n width: 100%;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-status {\n width: 24px;\n height: 24px;\n position: relative;\n}\n\n.tb-status.status-ok {\n background: transparent;\n border-radius: 4px;\n}\n\n.tb-status.status-ok:before {\n content: \"\";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n border-radius: 4px;\n background: var(--tb-primary-500);\n opacity: 0.04;\n}\n\n.tb-status:after {\n position: absolute;\n top: 2px;\n left: 2px;\n font-family: 'Material Icons Round';\n font-size: 20px;\n line-height: 1;\n}\n\n.tb-status.status-ok:after {\n content: \"check\";\n color: #198038;\n font-weight: 600;\n}\n\n.tb-status.status-warn:after {\n content: \"warning\";\n color: #FAA405;\n}\n\n.tb-status.status-critical:after {\n content: \"warning\";\n color: #D12730;\n}\n\n.tb-value-container {\n user-select: none;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 600;\n font-size: 20px;\n line-height: 24px;\n}\n\n.tb-total {\n padding-left: 4px;\n font-weight: 400;\n font-size: 12px;\n line-height: 16px;\n color: rgba(0, 0, 0, 0.54);\n}\n" - }, - "title": "System info mobile card", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "bcde0229-2463-00ee-b602-6f8d9280228d", - "typeFullFqn": "system.cards.markdown_card" - }, - "2a94a2ed-e2b9-4cac-ba10-f7d15508762c": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "rgba(0,0,0,0)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n \n \n \n
", - "applyDefaultMarkdownStyle": false - }, - "title": "System info cards", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": { - "border": "none", - "boxShadow": "none", - "padding": "0" - }, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "2a94a2ed-e2b9-4cac-ba10-f7d15508762c", - "typeFullFqn": "system.cards.markdown_card" - }, - "86d179f7-a4f7-39e4-ecbf-a1027bb32337": { - "typeFullFqn": "system.time_series_chart", - "type": "timeseries", - "sizeX": 8, - "sizeY": 5, - "config": { - "datasources": [ - { - "type": "entity", - "name": "", - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "dataKeys": [ - { - "name": "transportMsgCountHourly", - "type": "timeseries", - "label": "{i18n:widgets.transport-messages.title}", - "color": "var(--tb-primary-500)", - "settings": { - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "bar", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": false, - "lineType": "solid", - "lineWidth": 2, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "emptyCircle", - "pointSize": 4, - "fillAreaSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "yAxisId": "default" - }, - "decimals": 0 - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - }, - "latestDataKeys": [] - } - ], - "timewindow": { - "hideInterval": false, - "hideLastInterval": false, - "hideQuickInterval": false, - "hideAggregation": true, - "hideAggInterval": false, - "hideTimezone": false, - "selectedTab": 1, - "history": { - "historyType": 0, - "timewindowMs": 2592000000, - "interval": 86400000, - "fixedTimewindow": { - "startTimeMs": 1709807941444, - "endTimeMs": 1709894341444 - }, - "quickInterval": "CURRENT_DAY" - }, - "aggregation": { - "type": "SUM", - "limit": 25000 - }, - "timezone": null - }, - "showTitle": false, - "backgroundColor": "rgba(0, 0, 0, 0)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "yAxes": { - "default": { - "units": null, - "decimals": 0, - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "left", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormatter": "return value === 0 ? value : ((value / 1000) + 'k');", - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)", - "id": "default", - "order": 0, - "min": 0, - "max": null - } - }, - "thresholds": [], - "dataZoom": false, - "stack": false, - "xAxis": { - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "bottom", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 10, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormat": {}, - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)" - }, - "noAggregationBarWidthSettings": { - "strategy": "group", - "groupWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - }, - "barWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - } - }, - "showLegend": false, - "legendLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "legendLabelColor": "rgba(0, 0, 0, 0.76)", - "legendConfig": { - "direction": "column", - "position": "top", - "sortDataKeys": false, - "showMin": false, - "showMax": false, - "showAvg": true, - "showTotal": false, - "showLatest": false - }, - "showTooltip": true, - "tooltipTrigger": "axis", - "tooltipValueFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "500", - "lineHeight": "16px" - }, - "tooltipValueColor": "rgba(0, 0, 0, 0.76)", - "tooltipShowDate": true, - "tooltipDateFormat": { - "format": null, - "lastUpdateAgo": false, - "custom": false, - "auto": true, - "autoDateFormatSettings": {} - }, - "tooltipDateFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "tooltipDateColor": "rgba(0, 0, 0, 0.76)", - "tooltipDateInterval": false, - "tooltipBackgroundColor": "rgba(255, 255, 255, 0.76)", - "tooltipBackgroundBlur": 4, - "animation": { - "animation": true, - "animationThreshold": 2000, - "animationDuration": 1000, - "animationEasing": "cubicOut", - "animationDelay": 0, - "animationDurationUpdate": 300, - "animationEasingUpdate": "cubicOut", - "animationDelayUpdate": 0 - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - }, - "padding": "0" - }, - "title": "Time series chart", - "dropShadow": false, - "enableFullscreen": false, - "titleStyle": null, - "configMode": "basic", - "actions": {}, - "showTitleIcon": false, - "titleIcon": "thermostat", - "iconColor": "#1F6BDD", - "useDashboardTimewindow": false, - "displayTimewindow": true, - "titleFont": { - "size": 16, - "sizeUnit": "px", - "family": "Roboto", - "weight": "500", - "style": "normal", - "lineHeight": "24px" - }, - "titleColor": "rgba(0, 0, 0, 0.87)", - "titleTooltip": "", - "widgetStyle": {}, - "widgetCss": ".tb-widget-container > .tb-widget {\n border: none !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n}\n\n.tb-time-series-chart-panel div.tb-widget-title {\n padding-top: 5px;\n padding-left: 5px;\n}", - "pageSize": 1024, - "units": "", - "decimals": null, - "noDataDisplayMessage": "", - "timewindowStyle": { - "showIcon": true, - "iconSize": "24px", - "icon": "query_builder", - "iconPosition": "left", - "font": { - "size": 14, - "sizeUnit": "px", - "family": "Roboto", - "weight": "400", - "style": "normal", - "lineHeight": "16px" - }, - "color": "rgba(0, 0, 0, 0.54)", - "displayTypePrefix": true - }, - "margin": "0px", - "borderRadius": "0px", - "iconSize": "0px", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "86d179f7-a4f7-39e4-ecbf-a1027bb32337" - }, - "ac987854-1837-e585-7ce6-3c9e5069fbe2": { - "typeFullFqn": "system.time_series_chart", - "type": "timeseries", - "sizeX": 8, - "sizeY": 5, - "config": { - "datasources": [ - { - "type": "entity", - "name": "", - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "dataKeys": [ - { - "name": "cpuUsage", - "type": "timeseries", - "label": "{i18n:widgets.system-info.cpu}", - "color": "#305680", - "settings": { - "yAxisId": "default", - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "line", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": true, - "lineType": "solid", - "lineWidth": 3, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "circle", - "pointSize": 14, - "fillAreaSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - } - }, - "decimals": null, - "aggregationType": null, - "units": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - }, - { - "name": "memoryUsage", - "type": "timeseries", - "label": "{i18n:widgets.system-info.ram}", - "color": "#AC3BC9", - "settings": { - "yAxisId": "default", - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "line", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": true, - "lineType": "solid", - "lineWidth": 3, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "circle", - "pointSize": 14, - "fillAreaSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - } - }, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - }, - { - "name": "discUsage", - "type": "timeseries", - "label": "{i18n:widgets.system-info.disk}", - "color": "#40D0AE", - "settings": { - "yAxisId": "default", - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "line", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": true, - "lineType": "solid", - "lineWidth": 3, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "circle", - "pointSize": 14, - "fillAreaSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - } - }, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - }, - "latestDataKeys": [] - } - ], - "timewindow": { - "hideInterval": false, - "hideLastInterval": false, - "hideQuickInterval": false, - "hideAggregation": false, - "hideAggInterval": false, - "hideTimezone": false, - "selectedTab": 0, - "realtime": { - "realtimeType": 0, - "timewindowMs": 3600000, - "quickInterval": "CURRENT_DAY", - "interval": 10000 - }, - "aggregation": { - "type": "AVG", - "limit": 25000 - }, - "timezone": null - }, - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "8px", - "settings": { - "yAxes": { - "default": { - "units": null, - "decimals": 0, - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "left", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormatter": "", - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)", - "id": "default", - "order": 0, - "min": 0, - "max": 100 - } - }, - "thresholds": [], - "dataZoom": false, - "stack": false, - "xAxis": { - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "bottom", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 10, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormat": {}, - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)" - }, - "noAggregationBarWidthSettings": { - "strategy": "group", - "groupWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - }, - "barWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - } - }, - "showLegend": true, - "legendLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "legendLabelColor": "rgba(0, 0, 0, 0.76)", - "legendConfig": { - "direction": "column", - "position": "top", - "sortDataKeys": false, - "showMin": false, - "showMax": false, - "showAvg": false, - "showTotal": false, - "showLatest": false - }, - "showTooltip": true, - "tooltipTrigger": "axis", - "tooltipValueFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "500", - "lineHeight": "16px" - }, - "tooltipValueColor": "rgba(0, 0, 0, 0.76)", - "tooltipShowDate": true, - "tooltipDateFormat": { - "format": null, - "lastUpdateAgo": false, - "custom": false, - "auto": true, - "autoDateFormatSettings": {} - }, - "tooltipDateFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "tooltipDateColor": "rgba(0, 0, 0, 0.76)", - "tooltipDateInterval": false, - "tooltipBackgroundColor": "rgba(255, 255, 255, 0.76)", - "tooltipBackgroundBlur": 4, - "animation": { - "animation": true, - "animationThreshold": 2000, - "animationDuration": 300, - "animationEasing": "cubicOut", - "animationDelay": 0, - "animationDurationUpdate": 300, - "animationEasingUpdate": "cubicOut", - "animationDelayUpdate": 0 - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - }, - "padding": "0" - }, - "title": "Time series chart", - "dropShadow": false, - "enableFullscreen": false, - "titleStyle": null, - "configMode": "basic", - "actions": {}, - "showTitleIcon": false, - "titleIcon": "thermostat", - "iconColor": "#1F6BDD", - "useDashboardTimewindow": false, - "displayTimewindow": true, - "titleFont": { - "size": 16, - "sizeUnit": "px", - "family": "Roboto", - "weight": "500", - "style": "normal", - "lineHeight": "24px" - }, - "titleColor": "rgba(0, 0, 0, 0.87)", - "titleTooltip": "", - "widgetStyle": {}, - "widgetCss": ".tb-time-series-chart-panel div.tb-widget-title {\n padding-top: 5px;\n padding-left: 5px;\n}", - "pageSize": 1024, - "units": "%", - "decimals": null, - "noDataDisplayMessage": "", - "timewindowStyle": { - "showIcon": true, - "iconSize": "24px", - "icon": "query_builder", - "iconPosition": "left", - "font": { - "size": 14, - "sizeUnit": "px", - "family": "Roboto", - "weight": "400", - "style": "normal", - "lineHeight": "16px" - }, - "color": "rgba(0, 0, 0, 0.54)", - "displayTypePrefix": true - }, - "margin": "0px", - "borderRadius": "", - "iconSize": "0px", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "ac987854-1837-e585-7ce6-3c9e5069fbe2" - }, - "c02d59a0-c979-5ec6-7f58-a5d89ff66236": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 3 - }, - "title": "Getting started", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "noDataDisplayMessage": "", - "enableDataExport": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "c02d59a0-c979-5ec6-7f58-a5d89ff66236", - "typeFullFqn": "system.home_page_widgets.getting_started" - }, - "53d5f2dd-d432-5362-745f-63bf4487dc96": { - "typeFullFqn": "system.mobile_app_qr_code", - "type": "static", - "sizeX": 6, - "sizeY": 3, - "config": { - "showTitle": true, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useSystemSettings": true, - "qrCodeConfig": { - "badgeEnabled": true, - "badgePosition": "RIGHT", - "qrCodeLabelEnabled": true, - "qrCodeLabel": "Scan to connect or download mobile app" - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - } - }, - "title": "{i18n:admin.mobile-app.connect-mobile-app}", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": " .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n padding: 0;\n}\n\n .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n padding-bottom: 8px;\n font-weight: 600;\n font-size: 20px;\n line-height: 24px;\n letter-spacing: 0.1px;\n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel {\n padding: 0;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n padding-bottom: 0;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1190px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel {\n gap: 0;\n }\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n min-width: 150px;\n }\n}\n\n@media screen and (max-width: 960px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n max-width: 110px;\n }\n \n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-badges {\n max-width: 140px;\n }\n}\n\n@media screen and (min-width: 1819px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n max-width: 125px;\n }\n \n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-badges {\n max-width: 160px;\n }\n}\n\n@media screen and (min-width: 960px) and (max-height: 960px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode-label {\n display: none;\n }\n}", - "showTitleIcon": false, - "titleTooltip": "", - "titleStyle": null, - "borderRadius": "12px", - "enableDataExport": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "53d5f2dd-d432-5362-745f-63bf4487dc96" - }, - "0d34fa85-914f-30de-e3dd-7b7879f8d593": { - "typeFullFqn": "system.cards.markdown_card", - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextPattern": "### Markdown/HTML card\n - **Current entity**: ${entityName}.\n - **Current value**: ${Random}.", - "markdownTextFunction": "let html = '
';\nlet supportMobile = '${mobileQrEnabled:valuePlaceholder}';\nlet supportMobileValue = supportMobile.match(/\\${mobileQrEnabled:([^}]+)}/)[1];\nif (supportMobileValue === 'true') {\n ctx.dashboardWidget.widgetLayout.mobileHide = false;\n html += '';\n} else {\n ctx.dashboardWidget.widgetLayout.mobileHide = true;\n html += '';\n}\nhtml += '
';\nreturn html;", - "applyDefaultMarkdownStyle": false, - "markdownCss": "" - }, - "title": "Select show mobile QR code", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": { - "border": "none", - "boxShadow": "none", - "padding": 0 - }, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "widgetCss": "", - "noDataDisplayMessage": "", - "enableDataExport": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "0d34fa85-914f-30de-e3dd-7b7879f8d593" - } - }, - "states": { - "default": { - "name": "System Administrator Home Page", - "root": true, - "layouts": { - "main": { - "widgets": { - "d70cc256-4c7b-ee06-9905-b8c5e546605f": { - "sizeX": 41, - "sizeY": 16, - "row": 26, - "col": 44, - "mobileOrder": 7, - "mobileHeight": 8 - }, - "4b5e47ed-c197-a937-d727-041ba8decec2": { - "sizeX": 41, - "sizeY": 26, - "row": 0, - "col": 44, - "mobileOrder": 6, - "mobileHeight": 11 - }, - "d2784f6c-0518-fd95-1d28-b21f70bdcb10": { - "sizeX": 44, - "sizeY": 13, - "row": 29, - "col": 0, - "mobileOrder": 8, - "mobileHeight": 8 - }, - "66dcf1a2-9d83-6873-c693-d6a5d989b3f8": { - "sizeX": 24, - "sizeY": 16, - "row": 42, - "col": 0, - "mobileOrder": 9, - "mobileHeight": 7 - }, - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "sizeX": 44, - "sizeY": 14, - "row": 15, - "col": 0, - "mobileHide": true - }, - "a17ef013-1fcf-53e1-a9ac-770668dcaed0": { - "sizeX": 61, - "sizeY": 16, - "row": 42, - "col": 24, - "mobileHide": true - }, - "3f10c1f8-a990-b0e8-bbfe-f4f92b0901c2": { - "sizeX": 44, - "sizeY": 15, - "mobileOrder": 0, - "mobileHeight": 7, - "row": 0, - "col": 0 - }, - "0d34fa85-914f-30de-e3dd-7b7879f8d593": { - "sizeX": 35, - "sizeY": 58, - "row": 0, - "col": 85, - "mobileHide": false, - "mobileHeight": 7 - } - }, - "gridSettings": { - "backgroundColor": "#eeeeee", - "columns": 120, - "margin": 12, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 20, - "outerMargin": true, - "layoutType": "default" - } - } - } - }, - "transport_messages": { - "name": "Transport messages", - "root": false, - "layouts": { - "main": { - "widgets": { - "86d179f7-a4f7-39e4-ecbf-a1027bb32337": { - "sizeX": 24, - "sizeY": 11, - "row": 0, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "#ffffff", - "columns": 24, - "margin": 0, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "outerMargin": true, - "layoutType": "default" - } - } - } - }, - "monolith_system_info": { - "name": "Monolith System Info", - "root": false, - "layouts": { - "main": { - "widgets": { - "2a94a2ed-e2b9-4cac-ba10-f7d15508762c": { - "sizeX": 48, - "sizeY": 8, - "mobileOrder": 0, - "mobileHeight": 4, - "row": 0, - "col": 0 - }, - "ac987854-1837-e585-7ce6-3c9e5069fbe2": { - "sizeX": 48, - "sizeY": 20, - "row": 8, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "rgba(0,0,0,0)", - "columns": 48, - "margin": 12, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "outerMargin": false, - "layoutType": "default" - } - } - } - }, - "entities_info_desktop": { - "name": "Entities Info Desktop", - "root": false, - "layouts": { - "main": { - "widgets": { - "025868f4-ca7a-8f92-6025-8815a55541b8": { - "sizeX": 60, - "sizeY": 29, - "row": 0, - "col": 0 - }, - "bcb4bd75-2999-648d-d802-fda90ada07ab": { - "sizeX": 60, - "sizeY": 29, - "row": 0, - "col": 60 - }, - "5fb122d1-a399-ce8e-8bb8-d2710dd98c18": { - "sizeX": 30, - "sizeY": 26, - "row": 29, - "col": 0 - }, - "5c3d9d58-dd36-1ff3-b304-87345c6fefd2": { - "sizeX": 30, - "sizeY": 26, - "row": 29, - "col": 30 - }, - "d8da4ee1-cd83-5387-2fc7-a2e3f4b6422c": { - "sizeX": 30, - "sizeY": 26, - "row": 29, - "col": 60 - }, - "6ade2191-7c3d-244e-43ff-51feaa9d1735": { - "sizeX": 30, - "sizeY": 26, - "row": 29, - "col": 90 - } - }, - "gridSettings": { - "backgroundColor": "rgba(0,0,0,0)", - "columns": 120, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 70, - "layoutType": "default" - } - } - } - }, - "entities_info_mobile": { - "name": "Entities Info Mobile", - "root": false, - "layouts": { - "main": { - "widgets": { - "ba2b1a0c-c125-b246-d75b-8bbfe726c9e7": { - "sizeX": 24, - "sizeY": 11, - "row": 0, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "rgba(0,0,0,0)", - "columns": 24, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "layoutType": "default" - } - } - } - }, - "system_info_desktop": { - "name": "System Info Desktop", - "root": false, - "layouts": { - "main": { - "widgets": { - "182cab27-6f94-7b5e-fc87-6cbdced3e24f": { - "sizeX": 8, - "sizeY": 3, - "row": 0, - "col": 0 - }, - "329a0477-ab07-efa1-f48f-6a3b5b7025a4": { - "sizeX": 8, - "sizeY": 3, - "row": 0, - "col": 8 - }, - "85cbbe9b-d6a1-fe82-b600-99ced2dd441f": { - "sizeX": 8, - "sizeY": 3, - "row": 0, - "col": 16 - } - }, - "gridSettings": { - "backgroundColor": "rgba(0,0,0,0)", - "columns": 24, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "layoutType": "default" - } - } - } - }, - "system_info_mobile": { - "name": "System Info Mobile", - "root": false, - "layouts": { - "main": { - "widgets": { - "bcde0229-2463-00ee-b602-6f8d9280228d": { - "sizeX": 24, - "sizeY": 3, - "row": 0, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "rgba(0,0,0,0)", - "columns": 24, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "layoutType": "default" - } - } - } - }, - "mobile_app_qr_code": { - "name": "Mobile App QR code", - "root": false, - "layouts": { - "main": { - "widgets": { - "c02d59a0-c979-5ec6-7f58-a5d89ff66236": { - "sizeX": 120, - "sizeY": 45, - "row": 0, - "col": 0, - "mobileHide": true - }, - "53d5f2dd-d432-5362-745f-63bf4487dc96": { - "sizeX": 120, - "sizeY": 17, - "row": 45, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "#eeeeee", - "columns": 120, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 20, - "layoutType": "default" - } - } - } - } - }, - "entityAliases": { - "ae870700-071f-b3bc-406c-16ba554c5a55": { - "id": "ae870700-071f-b3bc-406c-16ba554c5a55", - "alias": "Tenants", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "TENANT" - } - }, - "ca4d90e4-f9ae-6fca-6b09-85815a48d52b": { - "id": "ca4d90e4-f9ae-6fca-6b09-85815a48d52b", - "alias": "TenantProfiles", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "TENANT_PROFILE" - } - }, - "a1ddb8fa-90ff-5598-e7f2-e254194d055d": { - "id": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "alias": "Devices", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "DEVICE" - } - }, - "619cdf00-a042-3b55-124e-194c1b28c236": { - "id": "619cdf00-a042-3b55-124e-194c1b28c236", - "alias": "Assets", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "ASSET" - } - }, - "1d97ff7f-8b42-5882-f87b-16f3d0dee4f2": { - "id": "1d97ff7f-8b42-5882-f87b-16f3d0dee4f2", - "alias": "Users", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "USER" - } - }, - "0dd2b154-59f4-0f97-da1a-d85f5b5cfe31": { - "id": "0dd2b154-59f4-0f97-da1a-d85f5b5cfe31", - "alias": "Customers", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "CUSTOMER" - } - }, - "d9229b29-3f46-de8d-7fe8-eb0c43c75079": { - "id": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "alias": "Api Usage State", - "filter": { - "type": "apiUsageState", - "resolveMultiple": true - } - } - }, - "filters": {}, - "timewindow": { - "selectedTab": 0, - "realtime": { - "realtimeType": 0, - "interval": 1000, - "timewindowMs": 60000 - }, - "aggregation": { - "type": "AVG" - } - }, - "settings": { - "stateControllerId": "entity", - "showTitle": false, - "showDashboardsSelect": true, - "showEntitiesSelect": true, - "showDashboardTimewindow": true, - "showDashboardExport": true, - "toolbarAlwaysOpen": true, - "titleColor": "rgba(0,0,0,0.870588)", - "showDashboardLogo": false, - "dashboardLogoUrl": null, - "hideToolbar": true, - "showFilters": true, - "showUpdateDashboardImage": true, - "dashboardCss": ".tb-widget-container > .tb-widget {\n border: 1px solid rgba(0, 0, 0, 0.05);\n box-shadow: 0px 5px 16px rgba(0, 0, 0, 0.04);\n border-radius: 12px;\n}\n\n.tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 16px !important;\n}\n\n.tb-card-title {\n display: grid;\n}\n\n.tb-home-widget-title {\n font-style: normal;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tb-home-widget-link {\n position: relative;\n border-bottom: none;\n}\n\n.tb-home-widget-link:hover {\n border-bottom: none;\n}\n\n.tb-home-widget-link:focus {\n border-bottom: none;\n}\n\n.tb-home-widget-link::after {\n content: 'arrow_forward';\n display: inline-block;\n transform: rotate(315deg);\n font-family: 'Material Icons';\n font-weight: normal;\n font-style: normal;\n font-size: 18px;\n color: rgba(0, 0, 0, 0.12);\n vertical-align: bottom;\n margin-left: 6px; \n}\n\n.tb-home-widget-link:hover::after {\n color: inherit;\n}\n\n.tb-home-widget-info-icon {\n color: rgba(0, 0, 0, 0.12);\n font-size: 16px;\n width: 16px;\n height: 16px;\n line-height: 15px;\n vertical-align: middle;\n}\n\n.tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n padding: 0;\n}\n\n.tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n cursor: pointer;\n user-select: none;\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1279px) {\n .tb-widget-container > .tb-widget {\n border-radius: 4px;\n }\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 2px !important;\n }\n .tb-hide-md {\n display: none;\n }\n}\n\n@media screen and (min-width: 1280px) and (max-width: 1819px) {\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 8px !important;\n }\n .tb-hide-lg {\n display: none;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-hide-md-lg {\n display: none;\n }\n\n .tb-home-widget-title {\n font-size: 12px;\n line-height: 16px;\n }\n \n .tb-widget-container > .tb-widget .tb-widget-title {\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 12px;\n line-height: 16px;\n min-height: 24px;\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 {\n width: 24px;\n height: 24px;\n line-height: 24px;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 .mat-icon {\n width: 18px;\n height: 18px;\n font-size: 18px;\n }\n \n .tb-widget-container > .tb-widget tb-legend {\n padding-bottom: 0 !important;\n }\n \n .tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n font-size: 11px;\n line-height: 16px;\n letter-spacing: 0.25px;\n }\n}\n\n@media screen and (max-width: 959px), screen and (min-width: 1820px) {\n .tb-hide-not-md-lg {\n display: none;\n }\n}\n" - } - }, - "name": "System Administrator Home Page" -} \ No newline at end of file diff --git a/ui-ngx/src/assets/dashboard/tenant_admin_home_page.json b/ui-ngx/src/assets/dashboard/tenant_admin_home_page.json deleted file mode 100644 index 51e09f3b12..0000000000 --- a/ui-ngx/src/assets/dashboard/tenant_admin_home_page.json +++ /dev/null @@ -1,1471 +0,0 @@ -{ - "title": "Tenant Administrator Home Page", - "image": null, - "mobileHide": false, - "mobileOrder": null, - "configuration": { - "description": "", - "widgets": { - "d70cc256-4c7b-ee06-9905-b8c5e546605f": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n \n
\n
{{ 'widgets.activity.title' | translate }}
\n \n {{ 'device.devices' | translate }}\n {{ 'widgets.transport-messages.title' | translate }}\n \n
\n \n \n \n \n \n \n \n \n
\n \n
\n
{{ 'widgets.activity.title' | translate }}
\n
\n
\n
\n
widgets.home.no-data-available
\n
\n
\n
\n", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n" - }, - "title": "Transport messages", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "d70cc256-4c7b-ee06-9905-b8c5e546605f", - "typeFullFqn": "system.cards.markdown_card" - }, - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "type": "static", - "sizeX": 7.5, - "sizeY": 3, - "config": { - "datasources": [], - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 2 - }, - "title": "Documentation", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false - }, - "row": 0, - "col": 0, - "id": "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4", - "typeFullFqn": "system.home_page_widgets.documentation_links" - }, - "ebbd0a6e-8a47-e770-5086-7f4974250f2d": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": {}, - "title": "New Usage info", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "ebbd0a6e-8a47-e770-5086-7f4974250f2d", - "typeFullFqn": "system.home_page_widgets.usage_info" - }, - "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e": { - "type": "static", - "sizeX": 7.5, - "sizeY": 3, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 2 - }, - "title": "Quick links", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e", - "typeFullFqn": "system.home_page_widgets.quick_links" - }, - "6d6e2b1d-6ce7-4678-3745-c6b0897b2674": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": {}, - "title": "Dashboards", - "dropShadow": true, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "6d6e2b1d-6ce7-4678-3745-c6b0897b2674", - "typeFullFqn": "system.home_page_widgets.dashboards" - }, - "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "totalDevices", - "color": "#2196f3", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": "42f42812-92fe-a13a-b0ba-c6e0dfab3584", - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "activeDevices", - "color": "#4caf50", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - }, - { - "type": "entityCount", - "name": null, - "entityAliasId": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "filterId": "39d92c21-2426-7346-4484-452829146c33", - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "inactiveDevices", - "color": "#f44336", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ] - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n gap: 12px;\n}\n\n.tb-content-container.tb-no-data {\n gap: 0;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-card-header.tb-no-data {\n height: auto;\n}\n\n.tb-item-cards {\n flex: 1;\n display: flex;\n flex-direction: row;\n gap: 12px;\n overflow: hidden;\n}\n\na.tb-item-card {\n flex: 1;\n display: flex;\n flex-direction: column;\n padding: 8px 12px;\n border: 1px solid;\n border-radius: 10px;\n margin-bottom: 12px;\n overflow: hidden;\n justify-content: space-evenly;\n}\n\na.tb-item-card.tb-inactive {\n background: rgba(209, 39, 48, 0.04);\n border-color: rgba(209, 39, 48, 0.06);\n}\n\na.tb-item-card.tb-active {\n position: relative;\n border: none;\n}\n\na.tb-item-card.tb-active::before {\n content: \"\";\n position: absolute;\n border-radius: 10px;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background: var(--tb-primary-500);\n opacity: 0.04;\n} \n\na.tb-item-card.tb-active .tb-active-border {\n content: \"\";\n position: absolute;\n border-radius: 10px;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background: transparent;\n border: 1px solid;\n border-color: var(--tb-primary-500);\n opacity: 0.12;\n}\n\na.tb-item-card.tb-total {\n background: rgba(0, 0, 0, 0.01);\n border-color: rgba(0, 0, 0, 0.05);\n}\n\n.tb-item-title-container {\n display: grid;\n}\n\n.tb-item-title {\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis; \n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-item-title.tb-home-widget-link:after {\n position: absolute;\n right: 0;\n}\n\na.tb-item-card:hover .tb-item-title.tb-home-widget-link:after { \n color: rgba(0, 0, 0, 0.38);\n}\n\na.tb-item-card:hover {\n box-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08);\n}\n\n.tb-count-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n justify-content: center;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 24px;\n line-height: 36px;\n white-space: nowrap;\n color: rgba(0, 0, 0, 0.87);\n}\n\n@media screen and (max-width: 959px) {\n .tb-item-cards {\n flex-direction: column;\n }\n a.tb-item-card {\n margin-bottom: 0;\n }\n}\n\n@media screen and (max-width: 1279px) {\n a.tb-item-card {\n flex-direction: row;\n align-items: center;\n }\n .tb-item-title.tb-home-widget-link:after {\n position: relative;\n }\n .tb-count-container {\n align-items: flex-end;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-item-title {\n font-size: 11px;\n line-height: 16px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n a.tb-item-card {\n padding: 4px 8px;\n margin-bottom: 6px;\n }\n a.tb-item-card:hover {\n box-shadow: 0px 2px 5px rgba(23, 33, 90, 0.08);\n }\n}\n" - }, - "title": "Devices", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6", - "typeFullFqn": "system.cards.markdown_card" - }, - "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb": { - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "datasources": [ - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "totalAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - } - }, - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "assignedToMeAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ], - "assignedToCurrentUser": true - } - }, - { - "type": "alarmCount", - "name": null, - "entityAliasId": null, - "filterId": null, - "dataKeys": [ - { - "name": "count", - "type": "count", - "label": "criticalAlarms", - "color": "#ffc107", - "settings": {}, - "aggregationType": null, - "units": null, - "decimals": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ], - "severityList": [ - "CRITICAL" - ] - } - } - ], - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useMarkdownTextFunction": false, - "markdownTextPattern": "", - "applyDefaultMarkdownStyle": false, - "markdownCss": ".tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n}\n\n.tb-content-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n gap: 12px;\n}\n\n.tb-content-container.tb-no-data {\n gap: 0;\n}\n\n.tb-card-header {\n height: 36px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n}\n\n.tb-card-header.tb-no-data {\n height: auto;\n}\n\n.tb-item-cards {\n flex: 1;\n display: flex;\n flex-direction: row;\n gap: 12px;\n overflow: hidden;\n}\n\na.tb-item-card {\n flex: 1;\n display: flex;\n flex-direction: column;\n padding: 8px 12px;\n border: 1px solid;\n border-radius: 10px;\n margin-bottom: 12px;\n overflow: hidden;\n justify-content: space-evenly;\n}\n\na.tb-item-card.tb-critical {\n background: rgba(209, 39, 48, 0.04);\n border-color: rgba(209, 39, 48, 0.06);\n}\n\na.tb-item-card.tb-assigned {\n position: relative;\n border: none;\n}\n\na.tb-item-card.tb-assigned::before {\n content: \"\";\n position: absolute;\n border-radius: 10px;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background: var(--tb-primary-500);\n opacity: 0.04;\n} \n\na.tb-item-card.tb-assigned .tb-assigned-border {\n content: \"\";\n position: absolute;\n border-radius: 10px;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background: transparent;\n border: 1px solid;\n border-color: var(--tb-primary-500);\n opacity: 0.12;\n}\n\na.tb-item-card.tb-total {\n background: rgba(0, 0, 0, 0.01);\n border-color: rgba(0, 0, 0, 0.05);\n}\n\n.tb-item-title-container {\n display: grid;\n}\n\n.tb-item-title {\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis; \n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-item-title.tb-home-widget-link:after {\n position: absolute;\n right: 0;\n}\n\na.tb-item-card:hover .tb-item-title.tb-home-widget-link:after { \n color: rgba(0, 0, 0, 0.38);\n}\n\na.tb-item-card:hover {\n box-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08);\n}\n\n.tb-count-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n justify-content: center;\n}\n\n.tb-count {\n font-style: normal;\n font-weight: 500;\n font-size: 24px;\n line-height: 36px;\n white-space: nowrap;\n color: rgba(0, 0, 0, 0.87);\n}\n\na.tb-item-card.tb-critical .tb-count:after {\n content: \"warning\";\n display: inline-block;\n position: relative;\n font-family: 'Material Icons Round';\n color: #D12730;\n vertical-align: bottom;\n margin-left: 6px;\n}\n\n@media screen and (max-width: 959px) {\n .tb-item-cards {\n flex-direction: column;\n }\n a.tb-item-card {\n margin-bottom: 0;\n }\n}\n\n@media screen and (max-width: 1279px) {\n a.tb-item-card {\n flex-direction: row;\n align-items: center;\n }\n .tb-item-title.tb-home-widget-link:after {\n position: relative;\n }\n .tb-count-container {\n align-items: flex-end;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-item-title {\n font-size: 11px;\n line-height: 16px;\n }\n .tb-count {\n font-size: 16px;\n line-height: 24px;\n }\n a.tb-item-card {\n padding: 4px 8px;\n margin-bottom: 6px;\n }\n a.tb-item-card:hover {\n box-shadow: 0px 2px 5px rgba(23, 33, 90, 0.08);\n }\n a.tb-item-card.tb-critical .tb-count:after {\n margin-left: 2px;\n }\n}\n" - }, - "title": "Alarms", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "showLegend": false, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb", - "typeFullFqn": "system.cards.markdown_card" - }, - "c007f42d-23eb-c0c2-9708-2fd380ce0b21": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": {}, - "title": "IoT Hub", - "dropShadow": true, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "pageSize": 1024, - "noDataDisplayMessage": "", - "showLegend": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "c007f42d-23eb-c0c2-9708-2fd380ce0b21", - "typeFullFqn": "system.home_page_widgets.iot_hub" - }, - "db892966-90f5-c506-77a3-61084772044c": { - "typeFullFqn": "system.time_series_chart", - "type": "timeseries", - "sizeX": 8, - "sizeY": 5, - "config": { - "datasources": [ - { - "type": "entity", - "name": "", - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "dataKeys": [ - { - "name": "activeDevicesCountHourly", - "type": "timeseries", - "label": "{i18n:device.devices}", - "color": "var(--tb-primary-500)", - "settings": { - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "line", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": true, - "lineType": "solid", - "lineWidth": 3, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "circle", - "pointSize": 14, - "fillAreaSettings": { - "type": "opacity", - "opacity": 0.04, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "yAxisId": "default" - }, - "decimals": 0, - "aggregationType": null, - "funcBody": null, - "usePostProcessing": null, - "postFuncBody": null - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - }, - "latestDataKeys": [] - } - ], - "timewindow": { - "hideInterval": false, - "hideLastInterval": false, - "hideQuickInterval": false, - "hideAggregation": true, - "hideAggInterval": true, - "hideTimezone": false, - "selectedTab": 1, - "history": { - "historyType": 0, - "timewindowMs": 2592000000, - "interval": 86400000, - "fixedTimewindow": { - "startTimeMs": 1709807941444, - "endTimeMs": 1709894341444 - }, - "quickInterval": "CURRENT_DAY" - }, - "aggregation": { - "type": "NONE", - "limit": 25000 - }, - "timezone": null - }, - "showTitle": false, - "backgroundColor": "rgba(0, 0, 0, 0)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "yAxes": { - "default": { - "units": null, - "decimals": 0, - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "left", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormatter": null, - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)", - "id": "default", - "order": 0, - "min": 0 - } - }, - "thresholds": [], - "dataZoom": false, - "stack": false, - "xAxis": { - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "bottom", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 10, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormat": {}, - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)" - }, - "noAggregationBarWidthSettings": { - "strategy": "group", - "groupWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - }, - "barWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - } - }, - "showLegend": false, - "legendLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "legendLabelColor": "rgba(0, 0, 0, 0.76)", - "legendConfig": { - "direction": "column", - "position": "top", - "sortDataKeys": false, - "showMin": false, - "showMax": false, - "showAvg": true, - "showTotal": false, - "showLatest": false - }, - "showTooltip": true, - "tooltipTrigger": "axis", - "tooltipValueFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "500", - "lineHeight": "16px" - }, - "tooltipValueColor": "rgba(0, 0, 0, 0.76)", - "tooltipShowDate": true, - "tooltipDateFormat": { - "format": null, - "lastUpdateAgo": false, - "custom": false, - "auto": true, - "autoDateFormatSettings": {} - }, - "tooltipDateFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "tooltipDateColor": "rgba(0, 0, 0, 0.76)", - "tooltipDateInterval": false, - "tooltipBackgroundColor": "rgba(255, 255, 255, 0.76)", - "tooltipBackgroundBlur": 4, - "animation": { - "animation": true, - "animationThreshold": 2000, - "animationDuration": 200, - "animationEasing": "cubicOut", - "animationDelay": 0, - "animationDurationUpdate": 300, - "animationEasingUpdate": "cubicOut", - "animationDelayUpdate": 0 - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - }, - "padding": "0" - }, - "title": "Time series chart", - "dropShadow": false, - "enableFullscreen": false, - "titleStyle": null, - "configMode": "basic", - "actions": {}, - "showTitleIcon": false, - "titleIcon": "thermostat", - "iconColor": "#1F6BDD", - "useDashboardTimewindow": false, - "displayTimewindow": true, - "titleFont": { - "size": 16, - "sizeUnit": "px", - "family": "Roboto", - "weight": "500", - "style": "normal", - "lineHeight": "24px" - }, - "titleColor": "rgba(0, 0, 0, 0.87)", - "titleTooltip": "", - "widgetStyle": {}, - "widgetCss": ".tb-widget-container > .tb-widget {\n border: none !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n}\n\n.tb-time-series-chart-panel div.tb-widget-title {\n padding-top: 5px;\n padding-left: 5px;\n}", - "pageSize": 1024, - "units": "", - "decimals": null, - "noDataDisplayMessage": "", - "timewindowStyle": { - "showIcon": true, - "iconSize": "24px", - "icon": "query_builder", - "iconPosition": "left", - "font": { - "size": 14, - "sizeUnit": "px", - "family": "Roboto", - "weight": "400", - "style": "normal", - "lineHeight": "16px" - }, - "color": "rgba(0, 0, 0, 0.54)", - "displayTypePrefix": true - }, - "margin": "0px", - "borderRadius": "0px", - "iconSize": "0px", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "db892966-90f5-c506-77a3-61084772044c" - }, - "c7d37465-9a6a-ab96-4fc8-791fb86ec8ac": { - "typeFullFqn": "system.time_series_chart", - "type": "timeseries", - "sizeX": 8, - "sizeY": 5, - "config": { - "datasources": [ - { - "type": "entity", - "name": "", - "entityAliasId": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "dataKeys": [ - { - "name": "transportMsgCountHourly", - "type": "timeseries", - "label": "{i18n:widgets.transport-messages.title}", - "color": "var(--tb-primary-500)", - "settings": { - "showInLegend": true, - "dataHiddenByDefault": false, - "type": "bar", - "lineSettings": { - "showLine": true, - "step": false, - "stepType": "start", - "smooth": false, - "lineType": "solid", - "lineWidth": 2, - "showPoints": false, - "showPointLabel": false, - "pointLabelPosition": "top", - "pointLabelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "pointLabelColor": "rgba(0, 0, 0, 0.76)", - "pointShape": "emptyCircle", - "pointSize": 4, - "fillAreaSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "barSettings": { - "showBorder": false, - "borderWidth": 2, - "borderRadius": 0, - "showLabel": false, - "labelPosition": "top", - "labelFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.76)", - "backgroundSettings": { - "type": "none", - "opacity": 0.4, - "gradient": { - "start": 100, - "end": 0 - } - } - }, - "yAxisId": "default" - }, - "decimals": 0 - } - ], - "alarmFilterConfig": { - "statusList": [ - "ACTIVE" - ] - }, - "latestDataKeys": [] - } - ], - "timewindow": { - "hideInterval": false, - "hideLastInterval": false, - "hideQuickInterval": false, - "hideAggregation": true, - "hideAggInterval": false, - "hideTimezone": false, - "selectedTab": 1, - "history": { - "historyType": 0, - "timewindowMs": 2592000000, - "interval": 86400000, - "fixedTimewindow": { - "startTimeMs": 1709807941444, - "endTimeMs": 1709894341444 - }, - "quickInterval": "CURRENT_DAY" - }, - "aggregation": { - "type": "SUM", - "limit": 25000 - }, - "timezone": null - }, - "showTitle": false, - "backgroundColor": "rgba(0, 0, 0, 0)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "yAxes": { - "default": { - "units": null, - "decimals": 0, - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "left", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormatter": "return value === 0 ? value : ((value / 1000) + 'k');", - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)", - "id": "default", - "order": 0, - "min": 0, - "max": null - } - }, - "thresholds": [], - "dataZoom": false, - "stack": false, - "xAxis": { - "show": true, - "label": "", - "labelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "600", - "lineHeight": "1" - }, - "labelColor": "rgba(0, 0, 0, 0.54)", - "position": "bottom", - "showTickLabels": true, - "tickLabelFont": { - "family": "Roboto", - "size": 10, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "1" - }, - "tickLabelColor": "rgba(0, 0, 0, 0.54)", - "ticksFormat": {}, - "showTicks": false, - "ticksColor": "rgba(0, 0, 0, 0.54)", - "showLine": false, - "lineColor": "rgba(0, 0, 0, 0.54)", - "showSplitLines": false, - "splitLinesColor": "rgba(0, 0, 0, 0.12)" - }, - "noAggregationBarWidthSettings": { - "strategy": "group", - "groupWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - }, - "barWidth": { - "relative": true, - "relativeWidth": 2, - "absoluteWidth": 1000 - } - }, - "showLegend": false, - "legendLabelFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "legendLabelColor": "rgba(0, 0, 0, 0.76)", - "legendConfig": { - "direction": "column", - "position": "top", - "sortDataKeys": false, - "showMin": false, - "showMax": false, - "showAvg": true, - "showTotal": false, - "showLatest": false - }, - "showTooltip": true, - "tooltipTrigger": "axis", - "tooltipValueFont": { - "family": "Roboto", - "size": 12, - "sizeUnit": "px", - "style": "normal", - "weight": "500", - "lineHeight": "16px" - }, - "tooltipValueColor": "rgba(0, 0, 0, 0.76)", - "tooltipShowDate": true, - "tooltipDateFormat": { - "format": null, - "lastUpdateAgo": false, - "custom": false, - "auto": true, - "autoDateFormatSettings": {} - }, - "tooltipDateFont": { - "family": "Roboto", - "size": 11, - "sizeUnit": "px", - "style": "normal", - "weight": "400", - "lineHeight": "16px" - }, - "tooltipDateColor": "rgba(0, 0, 0, 0.76)", - "tooltipDateInterval": false, - "tooltipBackgroundColor": "rgba(255, 255, 255, 0.76)", - "tooltipBackgroundBlur": 4, - "animation": { - "animation": true, - "animationThreshold": 2000, - "animationDuration": 1000, - "animationEasing": "cubicOut", - "animationDelay": 0, - "animationDurationUpdate": 300, - "animationEasingUpdate": "cubicOut", - "animationDelayUpdate": 0 - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - }, - "padding": "0" - }, - "title": "Time series chart", - "dropShadow": false, - "enableFullscreen": false, - "titleStyle": null, - "configMode": "basic", - "actions": {}, - "showTitleIcon": false, - "titleIcon": "thermostat", - "iconColor": "#1F6BDD", - "useDashboardTimewindow": false, - "displayTimewindow": true, - "titleFont": { - "size": 16, - "sizeUnit": "px", - "family": "Roboto", - "weight": "500", - "style": "normal", - "lineHeight": "24px" - }, - "titleColor": "rgba(0, 0, 0, 0.87)", - "titleTooltip": "", - "widgetStyle": {}, - "widgetCss": ".tb-widget-container > .tb-widget {\n border: none !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n}\n\n.tb-time-series-chart-panel div.tb-widget-title {\n padding-top: 5px;\n padding-left: 5px;\n}", - "pageSize": 1024, - "units": "", - "decimals": null, - "noDataDisplayMessage": "", - "timewindowStyle": { - "showIcon": true, - "iconSize": "24px", - "icon": "query_builder", - "iconPosition": "left", - "font": { - "size": 14, - "sizeUnit": "px", - "family": "Roboto", - "weight": "400", - "style": "normal", - "lineHeight": "16px" - }, - "color": "rgba(0, 0, 0, 0.54)", - "displayTypePrefix": true - }, - "margin": "0px", - "borderRadius": "0px", - "iconSize": "0px", - "enableDataExport": false - }, - "row": 0, - "col": 0, - "id": "c7d37465-9a6a-ab96-4fc8-791fb86ec8ac" - }, - "35bda856-2495-4f72-e35e-925bac8b8da7": { - "typeFullFqn": "system.cards.markdown_card", - "type": "latest", - "sizeX": 5, - "sizeY": 3.5, - "config": { - "showTitle": false, - "backgroundColor": "#fff", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "0px", - "settings": { - "useMarkdownTextFunction": true, - "markdownTextPattern": "### Markdown/HTML card\n - **Current entity**: ${entityName}.\n - **Current value**: ${Random}.", - "markdownTextFunction": "let html = '
';\nlet supportMobile = '${mobileQrEnabled:valuePlaceholder}';\nlet supportMobileValue = supportMobile.match(/\\${mobileQrEnabled:([^}]+)}/)[1];\nif (supportMobileValue === 'true') {\n ctx.dashboardWidget.widgetLayout.mobileHide = false;\n html += '';\n} else {\n ctx.dashboardWidget.widgetLayout.mobileHide = true;\n html += '';\n}\nhtml += '
';\nreturn html;", - "applyDefaultMarkdownStyle": false, - "markdownCss": "" - }, - "title": "Select show mobile QR code", - "showTitleIcon": false, - "iconColor": "rgba(0, 0, 0, 0.87)", - "iconSize": "24px", - "titleTooltip": "", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": { - "border": "none", - "boxShadow": "none", - "padding": 0 - }, - "titleStyle": { - "fontSize": "16px", - "fontWeight": 400 - }, - "widgetCss": "", - "noDataDisplayMessage": "", - "enableDataExport": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "35bda856-2495-4f72-e35e-925bac8b8da7" - }, - "ed33e56f-293b-aaaa-ad19-0cf499dc926f": { - "type": "static", - "sizeX": 7.5, - "sizeY": 6.5, - "config": { - "showTitle": false, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "columns": 3 - }, - "title": "Getting started", - "dropShadow": false, - "enableFullscreen": false, - "widgetStyle": {}, - "widgetCss": "", - "noDataDisplayMessage": "", - "enableDataExport": false, - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "ed33e56f-293b-aaaa-ad19-0cf499dc926f", - "typeFullFqn": "system.home_page_widgets.getting_started" - }, - "8c5207d8-7103-4dc2-db48-d61c0c8c61fd": { - "typeFullFqn": "system.mobile_app_qr_code", - "type": "static", - "sizeX": 6, - "sizeY": 3, - "config": { - "showTitle": true, - "backgroundColor": "rgb(255, 255, 255)", - "color": "rgba(0, 0, 0, 0.87)", - "padding": "16px", - "settings": { - "useSystemSettings": true, - "qrCodeConfig": { - "badgeEnabled": true, - "badgePosition": "RIGHT", - "qrCodeLabelEnabled": true, - "qrCodeLabel": "Scan to connect or download mobile app" - }, - "background": { - "type": "color", - "color": "#fff", - "overlay": { - "enabled": false, - "color": "rgba(255,255,255,0.72)", - "blur": 3 - } - } - }, - "title": "{i18n:admin.mobile-app.connect-mobile-app}", - "dropShadow": false, - "enableFullscreen": false, - "enableDataExport": false, - "widgetStyle": {}, - "widgetCss": " .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n padding: 0;\n}\n\n .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n font-weight: 600;\n font-size: 20px;\n line-height: 24px;\n letter-spacing: 0.1px;\n color: rgba(0, 0, 0, 0.76);\n}\n\n.tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel {\n padding: 0;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-widget-container > .tb-widget > .tb-widget-content .tb-widget-title > .title-row > .title {\n padding-bottom: 0;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1182px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel {\n gap: 0;\n }\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n min-width: 150px;\n }\n}\n\n@media screen and (max-width: 960px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n max-width: 120px;\n }\n \n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-badges {\n max-width: 160px;\n }\n}\n\n@media screen and (min-width: 1819px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode {\n max-width: 125px;\n }\n \n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-badges {\n max-width: 160px;\n }\n}\n\n@media screen and (min-width: 960px) and (max-height: 990px) {\n .tb-widget-container > .tb-widget > .tb-widget-content > .tb-widget .tb-mobile-app-qrcode-panel .tb-qrcode-label {\n display: none;\n }\n}", - "showTitleIcon": false, - "titleTooltip": "", - "titleStyle": null, - "borderRadius": "12px", - "datasources": [] - }, - "row": 0, - "col": 0, - "id": "8c5207d8-7103-4dc2-db48-d61c0c8c61fd" - } - }, - "states": { - "default": { - "name": "Tenant Administrator Home Page", - "root": true, - "layouts": { - "main": { - "widgets": { - "d70cc256-4c7b-ee06-9905-b8c5e546605f": { - "sizeX": 42, - "sizeY": 17, - "row": 27, - "col": 43, - "mobileOrder": 5, - "mobileHeight": 10 - }, - "867f82cf-ecf2-2d5c-35cb-08c6f2edc3a4": { - "sizeX": 29, - "sizeY": 14, - "row": 44, - "col": 28, - "mobileHide": true - }, - "ebbd0a6e-8a47-e770-5086-7f4974250f2d": { - "sizeX": 28, - "sizeY": 14, - "row": 44, - "col": 57, - "mobileOrder": 4, - "mobileHeight": 10 - }, - "9e3ef045-d8bc-1640-a3f4-2dd10b19d50e": { - "sizeX": 28, - "sizeY": 14, - "row": 44, - "col": 0, - "mobileHide": true - }, - "6d6e2b1d-6ce7-4678-3745-c6b0897b2674": { - "sizeX": 43, - "sizeY": 17, - "row": 27, - "col": 0, - "mobileOrder": 2, - "mobileHeight": 10 - }, - "35d3ac3b-f1af-dc3d-a1d1-11f351d16fc6": { - "sizeX": 43, - "sizeY": 12, - "row": 15, - "col": 0, - "mobileHeight": 9, - "mobileOrder": 1 - }, - "7ac20b6a-dc40-b18e-9f5f-bca20bc693bb": { - "sizeX": 42, - "sizeY": 12, - "mobileHeight": 9, - "row": 15, - "col": 43, - "mobileOrder": 0 - }, - "c007f42d-23eb-c0c2-9708-2fd380ce0b21": { - "sizeX": 85, - "sizeY": 15, - "row": 0, - "col": 0, - "mobileOrder": 3, - "mobileHeight": 12 - }, - "35bda856-2495-4f72-e35e-925bac8b8da7": { - "sizeX": 35, - "sizeY": 58, - "row": 0, - "col": 85, - "mobileHide": false, - "mobileHeight": 7 - } - }, - "gridSettings": { - "backgroundColor": "#eeeeee", - "columns": 120, - "margin": 12, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 20, - "outerMargin": true, - "layoutType": "default" - } - } - } - }, - "transport_messages": { - "name": "Transport messages", - "root": false, - "layouts": { - "main": { - "widgets": { - "c7d37465-9a6a-ab96-4fc8-791fb86ec8ac": { - "sizeX": 24, - "sizeY": 11, - "row": 0, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "#ffffff", - "columns": 24, - "margin": 0, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "outerMargin": true, - "layoutType": "default" - } - } - } - }, - "devices_activity": { - "name": "Devices activity", - "root": false, - "layouts": { - "main": { - "widgets": { - "db892966-90f5-c506-77a3-61084772044c": { - "sizeX": 24, - "sizeY": 11, - "row": 0, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "#ffffff", - "columns": 24, - "margin": 0, - "outerMargin": true, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": true, - "mobileRowHeight": 70, - "layoutType": "default" - } - } - } - }, - "mobile_app_qr_code": { - "name": "Mobile App QR code", - "root": false, - "layouts": { - "main": { - "widgets": { - "ed33e56f-293b-aaaa-ad19-0cf499dc926f": { - "sizeX": 120, - "sizeY": 47, - "row": 0, - "col": 0, - "mobileHide": true - }, - "8c5207d8-7103-4dc2-db48-d61c0c8c61fd": { - "sizeX": 120, - "sizeY": 15, - "row": 47, - "col": 0 - } - }, - "gridSettings": { - "backgroundColor": "#eeeeee", - "columns": 120, - "margin": 12, - "outerMargin": false, - "backgroundSizeMode": "100%", - "autoFillHeight": true, - "backgroundImageUrl": null, - "mobileAutoFillHeight": false, - "mobileRowHeight": 20, - "layoutType": "default" - } - } - } - } - }, - "entityAliases": { - "a1ddb8fa-90ff-5598-e7f2-e254194d055d": { - "id": "a1ddb8fa-90ff-5598-e7f2-e254194d055d", - "alias": "Devices", - "filter": { - "type": "entityType", - "resolveMultiple": true, - "entityType": "DEVICE" - } - }, - "d9229b29-3f46-de8d-7fe8-eb0c43c75079": { - "id": "d9229b29-3f46-de8d-7fe8-eb0c43c75079", - "alias": "Api Usage State", - "filter": { - "type": "apiUsageState", - "resolveMultiple": true - } - } - }, - "filters": { - "42f42812-92fe-a13a-b0ba-c6e0dfab3584": { - "id": "42f42812-92fe-a13a-b0ba-c6e0dfab3584", - "filter": "Active Devices", - "keyFilters": [ - { - "key": { - "type": "SERVER_ATTRIBUTE", - "key": "active" - }, - "valueType": "BOOLEAN", - "predicates": [ - { - "keyFilterPredicate": { - "operation": "EQUAL", - "value": { - "defaultValue": true, - "dynamicValue": null - }, - "type": "BOOLEAN" - }, - "userInfo": { - "editable": true, - "label": "", - "autogeneratedLabel": true, - "order": 0 - } - } - ] - } - ], - "editable": false - }, - "39d92c21-2426-7346-4484-452829146c33": { - "id": "39d92c21-2426-7346-4484-452829146c33", - "filter": "Inactive Devices", - "keyFilters": [ - { - "key": { - "type": "SERVER_ATTRIBUTE", - "key": "active" - }, - "valueType": "BOOLEAN", - "predicates": [ - { - "keyFilterPredicate": { - "operation": "EQUAL", - "value": { - "defaultValue": false, - "dynamicValue": null - }, - "type": "BOOLEAN" - }, - "userInfo": { - "editable": true, - "label": "", - "autogeneratedLabel": true, - "order": 0 - } - } - ] - } - ], - "editable": false - } - }, - "timewindow": { - "selectedTab": 0, - "realtime": { - "realtimeType": 0, - "interval": 1000, - "timewindowMs": 60000 - }, - "aggregation": { - "type": "AVG" - } - }, - "settings": { - "stateControllerId": "entity", - "showTitle": false, - "showDashboardsSelect": true, - "showEntitiesSelect": true, - "showDashboardTimewindow": true, - "showDashboardExport": true, - "toolbarAlwaysOpen": true, - "titleColor": "rgba(0,0,0,0.870588)", - "showDashboardLogo": false, - "dashboardLogoUrl": null, - "hideToolbar": true, - "showFilters": true, - "showUpdateDashboardImage": true, - "dashboardCss": ".tb-widget-container > .tb-widget {\n border: 1px solid rgba(0, 0, 0, 0.05);\n box-shadow: 0px 5px 16px rgba(0, 0, 0, 0.04);\n border-radius: 12px;\n}\n\n.tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 16px !important;\n}\n\n.tb-card-title {\n display: grid;\n}\n\n.tb-home-widget-title {\n font-style: normal;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.tb-home-widget-link {\n position: relative;\n border-bottom: none;\n}\n\n.tb-home-widget-link:hover {\n border-bottom: none;\n}\n\n.tb-home-widget-link:focus {\n border-bottom: none;\n}\n\n.tb-home-widget-link::after {\n content: 'arrow_forward';\n display: inline-block;\n transform: rotate(315deg);\n font-family: 'Material Icons';\n font-weight: normal;\n font-style: normal;\n font-size: 18px;\n color: rgba(0, 0, 0, 0.12);\n vertical-align: bottom;\n margin-left: 6px; \n}\n\n.tb-home-widget-link:hover::after {\n color: inherit;\n}\n\n.tb-home-widget-info-icon {\n color: rgba(0, 0, 0, 0.12);\n font-size: 16px;\n width: 16px;\n height: 16px;\n line-height: 15px;\n vertical-align: middle;\n}\n\n\n.tb-home-widget-no-data-available {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n}\n \n.tb-home-widget-no-data-bg {\n margin: 10px;\n position: relative;\n flex: 1;\n width: 100%;\n max-height: 100px;\n}\n\n.tb-home-widget-no-data-bg::before {\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--tb-primary-500);\n -webkit-mask-image: url(/assets/home/no_data_folder_bg.svg);\n -webkit-mask-repeat: no-repeat;\n -webkit-mask-size: contain;\n -webkit-mask-position: center;\n mask-image: url(/assets/home/no_data_folder_bg.svg);\n mask-repeat: no-repeat;\n mask-size: contain;\n mask-position: center;\n}\n\n.tb-home-widget-no-data-text {\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n.tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.25px;\n color: rgba(0, 0, 0, 0.54);\n padding: 0;\n}\n\n.tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n cursor: pointer;\n user-select: none;\n font-weight: 400;\n font-size: 14px;\n line-height: 20px;\n letter-spacing: 0.2px;\n color: rgba(0, 0, 0, 0.54);\n}\n\n@media screen and (min-width: 960px) and (max-width: 1279px) {\n .tb-widget-container > .tb-widget {\n border-radius: 4px;\n }\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 2px !important;\n }\n .tb-hide-md {\n display: none;\n }\n}\n\n@media screen and (min-width: 1280px) and (max-width: 1819px) {\n .tb-widget-container > .tb-widget:not([style*=\"padding: 0\"]) {\n padding: 8px !important;\n }\n .tb-hide-lg {\n display: none;\n }\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-hide-md-lg {\n display: none;\n }\n\n .tb-home-widget-title {\n font-size: 12px;\n line-height: 16px;\n }\n \n .tb-home-widget-no-data-text {\n font-size: 12px;\n line-height: 16px;\n }\n \n .tb-widget-container > .tb-widget .tb-widget-title {\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow {\n font-size: 12px;\n line-height: 16px;\n min-height: 24px;\n padding: 0;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 {\n width: 24px;\n height: 24px;\n line-height: 24px;\n }\n\n .tb-widget-container > .tb-widget .tb-timewindow .mat-mdc-icon-button.tb-mat-32 .mat-icon {\n width: 18px;\n height: 18px;\n font-size: 18px;\n }\n \n .tb-widget-container > .tb-widget tb-legend {\n padding-bottom: 0 !important;\n }\n \n .tb-widget-container > .tb-widget .tb-legend-keys .tb-legend-label {\n font-size: 11px;\n line-height: 16px;\n letter-spacing: 0.25px;\n }\n}\n\n@media screen and (max-width: 959px), screen and (min-width: 1820px) {\n .tb-hide-not-md-lg {\n display: none;\n }\n}\n" - } - }, - "name": "Tenant Administrator Home Page" -} diff --git a/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md b/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md new file mode 100644 index 0000000000..b08b5cbb3f --- /dev/null +++ b/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md @@ -0,0 +1,57 @@ +#### AI credits limit increase request notification templatization + +
+
+ +Notification subject and message fields support templatization. +The list of available templatization parameters depends on the template type. +See the available types and parameters below: + +Available template parameters: + +* `userEmail` - email of the user who sends the request; +* `tenantName` - name of the tenant whose users ran out of AI credits; +* `limitDescription` - which AI credits are used up, ex. 'its monthly limit of 5,000,000 AI credits' or 'all AI credits of this installation's license'; +* `increaseLimitActionLabel` - label of the button, 'Set new limit' or 'Add credits'; +* `increaseLimitLink` - link to the tenant page, or to the License Management page when the installation's AI credits are used up; +* `baseUrl` - used to construct the full URL of the link in email notifications; +* `recipientTitle` - title of the recipient (first and last name if specified, email otherwise); +* `recipientEmail` - email of the recipient; +* `recipientFirstName` - first name of the recipient; +* `recipientLastName` - last name of the recipient; + +Parameter names must be wrapped using `${...}`. For example: `${userEmail}`. +You may also modify the value of the parameter with one of the suffixes: + +* `upperCase`, for example - `${userEmail:upperCase}` +* `lowerCase`, for example - `${userEmail:lowerCase}` +* `capitalize`, for example - `${userEmail:capitalize}` + +To localize the notification, use `translate` suffix: `${some.translation.key:translate}` + +For example, if you have a custom translation key `custom.notifications.greetings` with value `Hello, ${recipientFirstName}!`, the template +`${custom.notifications.greetings:translate}` will be transformed to `Hello, John!`. +The needed locale is taken from recipient's profile settings, using English by default. + +
+ +##### Examples + +Let's assume the notification requesting more AI credits for the tenant 'Acme' that used its monthly limit. +The following template: + +```text +${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits. +{:copy-code} +``` + +will be transformed to: + +```text +johndoe@company.com from tenant Acme has used its monthly limit of 5,000,000 AI credits and is requesting more AI credits. +``` + +
+ +
+
diff --git a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json index b94fe3dbdc..9c291e931d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "التهيئة باستخدام الذكاء الاصطناعي", - "follow-up-prompt-placeholder": "ردّ...", - "sub-title": "يمكنني مساعدتك في إعداد وإدارة الأجهزة ولوحات المعلومات والحقول المحسوبة وقواعد الإنذار والإشعارات الخاصة بك — فقط صِف ما تحتاج إليه وسأتولى الباقي.", "new-chat": "محادثة جديدة", - "no-chats": "لا توجد محادثات بعد", "today": "اليوم", "yesterday": "الأمس", "last-7-days": "آخر 7 أيام", @@ -703,17 +700,11 @@ "delete-chat-title": "هل أنت متأكد أنك تريد حذف '{{name}}'؟", "delete-chat-text": "ستُفقد جميع رسائل المحادثة", "delete-chat-confirm": "نعم، احذف", - "action-approval-required": "الموافقة على الإجراء مطلوبة", "approve": "موافقة", - "approve-all": "الموافقة على جميع الإجراءات اللاحقة", "deny": "رفض", - "processing": "جارٍ المعالجة...", "approved": "تم", - "denied": "مرفوض", "error": "فشل", "thinking": "جارٍ التفكير...", - "connection-lost": "انقطع الاتصال بمساعد الذكاء الاصطناعي. جارٍ إعادة الاتصال...", - "reconnect-failed": "تعذّرت إعادة الاتصال بمساعد الذكاء الاصطناعي. أعد فتح المحادثة لرؤية ردّه.", "ask-the-assistant": "اسأل مساعد الذكاء الاصطناعي", "send": "إرسال", "new-line": "سطر جديد", @@ -740,9 +731,7 @@ "text": "نص", "file": "ملف" }, - "rename-chat-title": "إعادة تسمية هذه المحادثة", - "export-chat": "تصدير المحادثة", - "main-title": "مرحبًا! أنا مساعد الذكاء الاصطناعي الخاص بك" + "export-chat": "تصدير المحادثة" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "اقتراح قواعد إنذار", @@ -11319,47 +11308,20 @@ "select-recaptcha-enterprise-service-account-file": "اسحب ملف بيانات اعتماد حسابك وأفلته" }, "solution-creator": { - "ai-solution-creator": "مُنشئ الحلول بالذكاء الاصطناعي", "describe-solution-you-want": "صف الحل الذي تريد إنشاءه", - "enter-your-prompt": "أدخل مطالبتك", "target": "الهدف", "install-solution": "تثبيت", - "solution-overview": "نظرة عامة على الحل: {{ name }}", - "dashboards-overview": "نظرة عامة على لوحات المعلومات: {{ name }}", - "entity-profile": "ملف تعريف الكيان", - "entity-profiles": "ملفات تعريف الكيانات", - "name": "الاسم", - "iam": "IAM", - "iam-full": "إدارة الهوية والوصول", - "table-view": "جدول", - "schema-view": "مخطط", - "iam-info": "معلومات IAM", "operation": { "C": "إنشاء", "R": "قراءة", "U": "تحديث", "D": "حذف" }, - "alarm-info": "معلومات الإنذار", "description": "الوصف", - "data": "البيانات", - "entity-info": "معلومات الكيان", - "calculated-field-info": "معلومات الحقل المحسوب", - "field-type": "نوع الحقل", - "scope": "النطاق", "delete-alarm-title": "هل تريد حذف هذا الإنذار المقترح؟", "delete-alarm-text": "لن تتم إضافة هذا الإنذار، المقترح بناءً على وصفك، إلى بنية الحل المقترح.
يمكنك دائمًا تعديل الإنذارات أو إعادة إنشائها يدويًا لاحقًا. لا يمكن التراجع عن هذا الإجراء.", - "basic-mode": "أساسي", - "advanced-mode": "متقدم", "create-solution": "إنشاء الحل", "go-dashboard-manager": "التالي: تصميم لوحة المعلومات", - "success-generate-title": "الحل جاهز!", - "success-generate-sub-title": "يمكنك تثبيته على حسابك بالنقر على الزر أدناه", - "success-generate-install-title": "تم تثبيت الحل!", - "success-generate-install-sub-title": "لتعديل الحل، يرجى إلغاء تثبيت المثيل الحالي أولًا", - "main-title": "مرحبًا! أنا مساعد الذكاء الاصطناعي الخاص بك", - "sub-title": "أساعدك على تحويل متطلباتك إلى حل IoT متكامل وجاهز للعمل.\nما عليك سوى وصف ما تريد تحقيقه، وسأتولى الباقي.", - "solutions": "الحلول", "new-solution": "حل جديد", "uninstall-solution": "إلغاء التثبيت", "uninstall-solution-dialog-title": "هل أنت متأكد أنك تريد إلغاء تثبيت \"{{ name }}\"؟", @@ -11369,12 +11331,8 @@ "delete-solution-text": "ستفقد جميع بياناتك", "delete-solution-confirm": "نعم، حذف", "copy-solution": "نسخ الحل", - "expand-sidebar": "توسيع الشريط الجانبي", - "collapse-sidebar": "طي الشريط الجانبي", "solution-id": "معرّف الحل", "solution-id-required": "معرّف الحل مطلوب", - "rename-solution-title": "إعادة تسمية هذا الحل", - "generate-again": "إعادة التوليد", "skip-interview": "تخطي المقابلة", "update-solution": "تحديث الحل", "finish-edit": "إنهاء التعديل", @@ -11384,8 +11342,6 @@ "water-metering": "قياس استهلاك المياه", "coffee-machine-monitoring": "مراقبة آلات القهوة", "fleet-geofencing": "السياج الجغرافي للأسطول", - "more-examples": "المزيد من الأمثلة", - "hide": "إخفاء", "solution-info": "معلومات الحل", "solution-info-with-name": "معلومات الحل: {{ name }}", "status": "الحالة", @@ -11398,14 +11354,8 @@ "info": "معلومات", "main-dashboard": "لوحة المعلومات الرئيسية", "view-as": "عرض بصفة {{ name }}", - "generated-by-calculated-field-name": "تم إنشاؤه بواسطة الحقل المحسوب \"{{ name }}\"", "estimate-wait-time": "وقت الانتظار المقدّر ~{{ time }}", - "analyzing-your-request": "جارٍ تحليل طلبك...", "condition": "الشرط", - "installing": "جارٍ تثبيت الحل...", - "step-architecture-design": "تصميم البنية", - "step-dashboard-design": "تصميم لوحة المعلومات", - "step-solution-installation": "تثبيت الحل", "step-reading-device-data": "جارٍ قراءة بيانات الجهاز…", "step-analyzing-telemetry-attributes": "جارٍ تحليل القياس عن بُعد والسمات…", "step-selecting-widgets": "جارٍ اختيار الأدوات المناسبة لبياناتك…", @@ -11437,11 +11387,7 @@ "step-loading-building-alarm-rules": "جارٍ بناء قواعد الإنذار…", "step-loading-assembling-dashboards": "جارٍ تجميع لوحات المعلومات…", "step-loading-preparing-states": "جارٍ تحضير الحالات…", - "step-loading-initializing-solution": "جارٍ تهيئة الحل…", - "ai-credits": "أرصدة الذكاء الاصطناعي", - "ai-credits-update": "تغيير الخطة", - "ai-credits-usage": "أرصدة الذكاء الاصطناعي: تم استخدام {{ used }} من {{ max }}", - "ai-credits-description": "لقد استخدمت {{ used }} من أصل {{ max }} من أرصدة الذكاء الاصطناعي هذا الشهر. تتم إعادة تعيين الحد في {{ date }}. لزيادة حصتك من أرصدة الذكاء الاصطناعي، يرجى التواصل مع مسؤول النظام." + "step-loading-initializing-solution": "جارٍ تهيئة الحل…" }, "markdown": { "edit": "تعديل", @@ -13874,11 +13820,6 @@ "disk-warning-text": "انخفاض مساحة القرص المتاحة. لتجنب فقدان البيانات، حرِّر مساحة على القرص أو وسِّع مساحته.", "disk-critical-text": "انخفاض حرج في مساحة القرص المتاحة. لتجنب فقدان البيانات، حرِّر مساحة على القرص أو وسِّع مساحته." }, - "cluster-info": { - "service-id": "معرف الخدمة", - "service-type": "نوع الخدمة", - "no-data": "لا تتوفر بيانات" - }, "transport-messages": { "title": "رسائل النقل", "info": "كل الرسائل التي تأتي من الأجهزة" @@ -13917,41 +13858,9 @@ "no-last-viewed-dashboards": "لا توجد لوحات معلومات تمت مشاهدتها مؤخرًا بعد" }, "configured-features": { - "title": "الميزات المُكوَّنة", - "info": "حالة الميزات التي تتطلب تكوينًا", - "white-labeling-feature": "تخصيص العلامة التجارية", - "email-feature": "البريد الإلكتروني", - "sms-feature": "رسائل SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "المصادقة بخطوتين", "feature-configured": "الميزة مكونة.\nانقر لإعدادها", "feature-not-configured": "الميزة غير مكونة.\nانقر لإعدادها" }, - "version-info": { - "title": "الإصدار", - "contact-us": "اتصل بنا", - "current-version": "الإصدار الحالي", - "current": "الحالي", - "available-version": "الإصدار المتاح", - "available": "متاح", - "upgrade": "الترقية", - "version-is-up-to-date": "الإصدار محدَّث" - }, - "license-info": { - "title": "معلومات الترخيص", - "view-all": "عرض الكل", - "license-portal": "بوابة الترخيص", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } أجهزة", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } أصول", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } مثيلات Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } لوحات معلومات", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } تكاملات", - "community-support": "دعم المجتمع", - "white-labeling": "تخصيص العلامة التجارية", - "unlimited-datapoints-and-messages": "نقاط البيانات والرسائل غير محدودة", - "unlimited-api-calls": "استدعاءات API غير محدودة" - }, "usage-info": { "title": "استخدام", "entities": "الكيانات", diff --git a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json index 6b21ea6f4d..a1b31ddd1e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configura amb IA", - "follow-up-prompt-placeholder": "Respon...", - "sub-title": "Puc ajudar-vos a configurar i gestionar els vostres dispositius, taulers, camps calculats, regles d'alarma i notificacions: només heu de descriure què necessiteu i jo m'encarrego de la resta.", "new-chat": "Nou xat", - "no-chats": "Encara no hi ha xats", "today": "Avui", "yesterday": "Ahir", "last-7-days": "Últims 7 dies", @@ -703,17 +700,11 @@ "delete-chat-title": "Esteu segur que voleu suprimir '{{name}}'?", "delete-chat-text": "Es perdran tots els missatges del xat", "delete-chat-confirm": "Sí, suprimeix", - "action-approval-required": "Cal aprovar l'acció", "approve": "Aprova", - "approve-all": "Aprova totes les accions posteriors", "deny": "Denega", - "processing": "S'està processant...", "approved": "Fet", - "denied": "Denegat", "error": "Ha fallat", "thinking": "Pensant...", - "connection-lost": "S'ha perdut la connexió amb l'assistent d'IA. S'està tornant a connectar...", - "reconnect-failed": "No s'ha pogut tornar a connectar amb l'assistent d'IA. Torneu a obrir el xat per veure'n la resposta.", "ask-the-assistant": "Pregunteu a l'assistent d'IA", "send": "Envia", "new-line": "Línia nova", @@ -740,9 +731,7 @@ "text": "Text", "file": "Fitxer" }, - "rename-chat-title": "Canvia el nom d'aquest xat", - "export-chat": "Exporta el xat", - "main-title": "Hola! Soc el vostre assistent d'IA" + "export-chat": "Exporta el xat" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Suggereix regles d'alarma", @@ -11324,47 +11313,20 @@ "select-recaptcha-enterprise-service-account-file": "Arrossegueu i deixeu anar el fitxer de credencials del compte" }, "solution-creator": { - "ai-solution-creator": "Creador de solucions amb IA", "describe-solution-you-want": "Descriviu la solució que voleu crear", - "enter-your-prompt": "Introduïu la vostra indicació", "target": "Destinació", "install-solution": "Instal·la", - "solution-overview": "Resum de la solució: {{ name }}", - "dashboards-overview": "Resum dels taulers: {{ name }}", - "entity-profile": "Perfil d'entitat", - "entity-profiles": "Perfils d'entitat", - "name": "Nom", - "iam": "IAM", - "iam-full": "Gestió d'identitats i accessos", - "table-view": "Taula", - "schema-view": "Esquema", - "iam-info": "Informació d'IAM", "operation": { "C": "Crea", "R": "Llegeix", "U": "Actualitza", "D": "Suprimeix" }, - "alarm-info": "Informació de l'alarma", "description": "Descripció", - "data": "Dades", - "entity-info": "Informació de l'entitat", - "calculated-field-info": "Informació del camp calculat", - "field-type": "Tipus de camp", - "scope": "Àmbit", "delete-alarm-title": "Voleu suprimir aquesta alarma suggerida?", "delete-alarm-text": "Aquesta alarma, suggerida a partir de la vostra descripció, no s'afegirà a la construcció de la solució proposada.
Sempre podeu editar o tornar a crear les alarmes manualment més endavant. Aquesta acció no es pot desfer.", - "basic-mode": "Bàsic", - "advanced-mode": "Avançat", "create-solution": "Crea una solució", "go-dashboard-manager": "Següent: disseny del tauler", - "success-generate-title": "La solució està a punt!", - "success-generate-sub-title": "Podeu instal·lar-la al vostre compte fent clic al botó de sota", - "success-generate-install-title": "Solució instal·lada!", - "success-generate-install-sub-title": "Per editar la solució, primer desinstal·leu la instància existent", - "main-title": "Hola! Soc el vostre assistent d'IA", - "sub-title": "Us ajudo a transformar els vostres requisits en una solució IoT completament funcional.\nNomés cal que descriviu què voleu aconseguir, i jo m'encarrego de la resta.", - "solutions": "Solucions", "new-solution": "Solució nova", "uninstall-solution": "Desinstal·la", "uninstall-solution-dialog-title": "Esteu segur que voleu desinstal·lar ‘{{ name }}’?", @@ -11374,12 +11336,8 @@ "delete-solution-text": "Es perdran totes les vostres dades", "delete-solution-confirm": "Sí, suprimeix", "copy-solution": "Copia la solució", - "expand-sidebar": "Expandeix la barra lateral", - "collapse-sidebar": "Contrau la barra lateral", "solution-id": "ID de la solució", "solution-id-required": "L'ID de la solució és obligatori", - "rename-solution-title": "Canvia el nom d'aquesta solució", - "generate-again": "Torna a generar", "skip-interview": "Omet l'entrevista", "update-solution": "Actualitza la solució", "finish-edit": "Finalitza l'edició", @@ -11389,8 +11347,6 @@ "water-metering": "Mesurament del consum d'aigua", "coffee-machine-monitoring": "Monitoratge de màquines de cafè", "fleet-geofencing": "Geotancament de flotes", - "more-examples": "Més exemples", - "hide": "Amaga", "solution-info": "Informació de la solució", "solution-info-with-name": "Informació de la solució: {{ name }}", "status": "Estat", @@ -11403,14 +11359,8 @@ "info": "Informació", "main-dashboard": "Tauler principal", "view-as": "Visualitza com a {{ name }}", - "generated-by-calculated-field-name": "Generat pel camp calculat ‘{{ name }}’", "estimate-wait-time": "El temps d'espera estimat és de ~{{ time }}", - "analyzing-your-request": "S'està analitzant la vostra sol·licitud...", "condition": "Condició", - "installing": "S'està instal·lant la solució...", - "step-architecture-design": "Disseny de l'arquitectura", - "step-dashboard-design": "Disseny del tauler", - "step-solution-installation": "Instal·lació de la solució", "step-reading-device-data": "S'estan llegint les dades del dispositiu…", "step-analyzing-telemetry-attributes": "S'estan analitzant la telemetria i els atributs…", "step-selecting-widgets": "S'estan seleccionant ginys per a les vostres dades…", @@ -11442,11 +11392,7 @@ "step-loading-building-alarm-rules": "S'estan construint les regles d'alarma…", "step-loading-assembling-dashboards": "S'estan muntant els taulers…", "step-loading-preparing-states": "S'estan preparant els estats…", - "step-loading-initializing-solution": "S'està inicialitzant la solució…", - "ai-credits": "Crèdits d'IA", - "ai-credits-update": "Canvia el pla", - "ai-credits-usage": "Crèdits d'IA: {{ used }} de {{ max }} utilitzats", - "ai-credits-description": "Heu utilitzat {{ used }} dels vostres {{ max }} crèdits d'IA aquest mes. El límit es restableix el {{ date }}. Per augmentar la vostra quota de crèdits d'IA, contacteu amb l'administrador del sistema." + "step-loading-initializing-solution": "S'està inicialitzant la solució…" }, "markdown": { "edit": "Edita", @@ -13879,11 +13825,6 @@ "disk-warning-text": "Queda poc espai al disc. Per evitar la pèrdua de dades, allibereu o amplieu l'espai del disc.", "disk-critical-text": "Espai al disc críticament baix. Per evitar la pèrdua de dades, allibereu o amplieu l'espai del disc." }, - "cluster-info": { - "service-id": "ID del servei", - "service-type": "Tipus de servei", - "no-data": "No hi ha dades" - }, "transport-messages": { "title": "Missatges de transport", "info": "Tots els missatges que han arribat dels dispositius" @@ -13922,41 +13863,9 @@ "no-last-viewed-dashboards": "Encara no hi ha taulers vistos recentment" }, "configured-features": { - "title": "Funcionalitats configurades", - "info": "Estat de les funcionalitats que requereixen configuració", - "white-labeling-feature": "Marca blanca", - "email-feature": "Correu electrònic", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "La funcionalitat està configurada.\nFeu clic per configurar-la", "feature-not-configured": "La funcionalitat no està configurada.\nFeu clic per configurar-la" }, - "version-info": { - "title": "Versió", - "contact-us": "Contacteu-nos", - "current-version": "Versió actual", - "current": "Actual", - "available-version": "Versió disponible", - "available": "Disponible", - "upgrade": "Actualitza la versió", - "version-is-up-to-date": "La versió està actualitzada" - }, - "license-info": { - "title": "Informació de la llicència", - "view-all": "Mostra-ho tot", - "license-portal": "Portal de llicències", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } dispositius", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } actius", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } instàncies d'Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } taulers", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integracions", - "community-support": "Suport de la comunitat", - "white-labeling": "Marca blanca", - "unlimited-datapoints-and-messages": "Punts de dades i missatges il·limitats", - "unlimited-api-calls": "Crides a l'API il·limitades" - }, "usage-info": { "title": "Ús", "entities": "Entitats", diff --git a/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json b/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json index 801c079910..404ba066ee 100644 --- a/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json +++ b/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json @@ -243,10 +243,7 @@ }, "ai-assistant": { "configure-with-ai": "Nakonfigurovat pomocí AI", - "follow-up-prompt-placeholder": "Odpovědět...", - "sub-title": "Mohu vám pomoci nastavit a spravovat vaše zařízení, dashboardy, vypočítaná pole, pravidla alarmů a oznámení — stačí popsat, co potřebujete, a o zbytek se postarám.", "new-chat": "Nový chat", - "no-chats": "Zatím žádné chaty", "today": "Dnes", "yesterday": "Včera", "last-7-days": "Posledních 7 dní", @@ -254,16 +251,11 @@ "delete-chat-title": "Opravdu chcete smazat '{{name}}'?", "delete-chat-text": "Všechny zprávy chatu budou ztraceny", "delete-chat-confirm": "Ano, smazat", - "action-approval-required": "Vyžadováno schválení akce", "approve": "Schválit", "deny": "Zamítnout", - "processing": "Zpracovává se...", "approved": "Hotovo", - "denied": "Zamítnuto", "error": "Selhalo", - "thinking": "Přemýšlím...", - "rename-chat-title": "Přejmenovat tento chat", - "main-title": "Ahoj! Jsem váš AI asistent" + "thinking": "Přemýšlím..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Navrhnout pravidla alarmů", diff --git a/ui-ngx/src/assets/locale/locale.constant-da_DK.json b/ui-ngx/src/assets/locale/locale.constant-da_DK.json index 33d38f576a..965db063d3 100644 --- a/ui-ngx/src/assets/locale/locale.constant-da_DK.json +++ b/ui-ngx/src/assets/locale/locale.constant-da_DK.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurér med AI", - "follow-up-prompt-placeholder": "Svar...", - "sub-title": "Jeg kan hjælpe dig med at opsætte og administrere dine enheder, dashboards, beregnede felter, alarmregler og notifikationer — beskriv blot, hvad du har brug for, så klarer jeg resten.", "new-chat": "Ny chat", - "no-chats": "Ingen chats endnu", "today": "I dag", "yesterday": "I går", "last-7-days": "Sidste 7 dage", @@ -703,20 +700,12 @@ "delete-chat-title": "Er du sikker på, at du vil slette '{{name}}'?", "delete-chat-text": "Alle chatbeskeder vil gå tabt", "delete-chat-confirm": "Ja, slet", - "action-approval-required": "Godkendelse af handlingen påkrævet", "approve": "Godkend", - "approve-all": "Godkend alle yderligere handlinger", "deny": "Afvis", - "processing": "Behandler...", "approved": "Færdig", - "denied": "Afvist", "error": "Mislykkedes", "thinking": "Tænker...", - "connection-lost": "Forbindelsen til AI-assistenten blev afbrudt. Genopretter forbindelsen...", - "reconnect-failed": "Kunne ikke genoprette forbindelsen til AI-assistenten. Åbn chatten igen for at se svaret.", - "rename-chat-title": "Omdøb denne chat", - "export-chat": "Eksportér chat", - "main-title": "Hej! Jeg er din AI-assistent" + "export-chat": "Eksportér chat" }, "alarm": { "alarm": "Alarm", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Træk og slip din konto-legitimationsfil" }, "solution-creator": { - "ai-solution-creator": "AI-løsningsbygger", "describe-solution-you-want": "Beskriv den løsning, du vil lave", - "enter-your-prompt": "Indtast din prompt", "target": "Mål", "install-solution": "Installér", - "solution-overview": "Løsningsoversigt: {{ name }}", - "dashboards-overview": "Dashboardoversigt: {{ name }}", - "entity-profile": "Entitetsprofil", - "entity-profiles": "Entitetsprofiler", - "name": "Navn", - "iam": "IAM", - "iam-full": "Identitets- og adgangsstyring", - "table-view": "Tabel", - "schema-view": "Skema", - "iam-info": "IAM-info", "operation": { "C": "Opret", "R": "Læs", "U": "Opdatér", "D": "Slet" }, - "alarm-info": "Alarmoplysninger", "description": "Beskrivelse", - "data": "Data", - "entity-info": "Entitetsoplysninger", - "calculated-field-info": "Oplysninger om beregnet felt", - "field-type": "Felttype", - "scope": "Omfang", "delete-alarm-title": "Slet denne foreslåede alarm?", "delete-alarm-text": "Denne alarm, der er foreslået ud fra din beskrivelse, bliver ikke føjet til den foreslåede opbygning af løsningen.
Du kan altid redigere eller oprette alarmer igen manuelt senere. Denne handling kan ikke fortrydes.", - "basic-mode": "Grundlæggende", - "advanced-mode": "Avanceret", "create-solution": "Opret løsning", "go-dashboard-manager": "Næste: Dashboarddesign", - "success-generate-title": "Løsningen er klar!", - "success-generate-sub-title": "Du kan installere den på din konto ved at klikke på knappen nedenfor", - "success-generate-install-title": "Løsningen er installeret!", - "success-generate-install-sub-title": "For at redigere løsningen skal du først afinstallere den eksisterende instans", - "main-title": "Hej! Jeg er din AI-assistent", - "sub-title": "Jeg hjælper dig med at omsætte dine krav til en fuldt funktionel IoT-løsning.\nBeskriv bare, hvad du vil opnå, så klarer jeg resten.", - "solutions": "Løsninger", "new-solution": "Ny løsning", "uninstall-solution": "Afinstallér", "uninstall-solution-dialog-title": "Er du sikker på, at du vil afinstallere ‘{{ name }}’?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "Alle dine data vil gå tabt", "delete-solution-confirm": "Ja, slet", "copy-solution": "Kopiér løsning", - "expand-sidebar": "Udvid sidepanel", - "collapse-sidebar": "Skjul sidepanel", "solution-id": "Løsnings-ID", "solution-id-required": "Løsnings-ID er påkrævet", - "rename-solution-title": "Omdøb denne løsning", - "generate-again": "Generér igen", "skip-interview": "Spring interview over", "update-solution": "Opdatér løsning", "finish-edit": "Afslut redigering", @@ -11300,8 +11258,6 @@ "water-metering": "Vandmåling", "coffee-machine-monitoring": "Overvågning af kaffemaskiner", "fleet-geofencing": "Geofencing af flåder", - "more-examples": "Flere eksempler", - "hide": "Skjul", "solution-info": "Løsningsinfo", "solution-info-with-name": "Løsningsinfo: {{ name }}", "status": "Status", @@ -11314,14 +11270,8 @@ "info": "Info", "main-dashboard": "Hoveddashboard", "view-as": "Vis som {{ name }}", - "generated-by-calculated-field-name": "Genereret af det beregnede felt ‘{{ name }}’", "estimate-wait-time": "Anslået ventetid er ~{{ time }}", - "analyzing-your-request": "Analyserer din anmodning...", "condition": "Betingelse", - "installing": "Installerer løsning...", - "step-architecture-design": "Arkitekturdesign", - "step-dashboard-design": "Dashboarddesign", - "step-solution-installation": "Løsningsinstallation", "step-reading-device-data": "Læser enhedsdata…", "step-analyzing-telemetry-attributes": "Analyserer telemetri og attributter…", "step-selecting-widgets": "Vælger widgets til dine data…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "Opbygger alarmregler…", "step-loading-assembling-dashboards": "Samler dashboards…", "step-loading-preparing-states": "Forbereder tilstande…", - "step-loading-initializing-solution": "Initialiserer løsning…", - "ai-credits": "AI-kreditter", - "ai-credits-update": "Skift plan", - "ai-credits-usage": "AI-kreditter: {{ used }} af {{ max }} brugt", - "ai-credits-description": "Du har brugt {{ used }} af dine {{ max }} AI-kreditter denne måned. Grænsen nulstilles den {{ date }}. Kontakt din systemadministrator for at øge din grænse for AI-kreditter." + "step-loading-initializing-solution": "Initialiserer løsning…" }, "markdown": { "edit": "Redigér", @@ -13783,11 +13729,6 @@ "disk-warning-text": "Lav diskplads. Frigør eller udvid diskpladsen for at undgå datatab.", "disk-critical-text": "Kritisk lav diskplads. Frigør eller udvid diskpladsen for at undgå datatab." }, - "cluster-info": { - "service-id": "Service-id", - "service-type": "Servicetype", - "no-data": "Ingen data" - }, "transport-messages": { "title": "Transportbeskeder", "info": "Alle beskeder der kommer fra enheder" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "Ingen dashboards er blevet vist endnu" }, "configured-features": { - "title": "Konfigurerede funktioner", - "info": "Status for funktioner, der kræver konfiguration", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funktionen er konfigureret.\nKlik for at opsætte", "feature-not-configured": "Funktionen er ikke konfigureret.\nKlik for at opsætte" }, - "version-info": { - "title": "Version", - "contact-us": "Kontakt os", - "current-version": "Nuværende version", - "current": "Aktuel", - "available-version": "Tilgængelig version", - "available": "Tilgængelig", - "upgrade": "Opgradér", - "version-is-up-to-date": "Du har den nyeste version" - }, - "license-info": { - "title": "Licensinfo", - "view-all": "Se alle", - "license-portal": "Licensportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Enheder", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Aktiver", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrationer", - "community-support": "Fællesskabssupport", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Ubegrænsede datapunkter og beskeder", - "unlimited-api-calls": "Ubegrænsede API-kald" - }, "usage-info": { "title": "Forbrug", "entities": "Entiteter", diff --git a/ui-ngx/src/assets/locale/locale.constant-de_DE.json b/ui-ngx/src/assets/locale/locale.constant-de_DE.json index ddd4ddff2f..08f58a3e87 100644 --- a/ui-ngx/src/assets/locale/locale.constant-de_DE.json +++ b/ui-ngx/src/assets/locale/locale.constant-de_DE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Mit KI konfigurieren", - "follow-up-prompt-placeholder": "Antworten...", - "sub-title": "Ich helfe Ihnen beim Einrichten und Verwalten Ihrer Geräte, Dashboards, berechneten Felder, Alarmregeln und Benachrichtigungen – beschreiben Sie einfach, was Sie brauchen, und ich erledige den Rest.", "new-chat": "Neuer Chat", - "no-chats": "Noch keine Chats", "today": "Heute", "yesterday": "Gestern", "last-7-days": "Letzte 7 Tage", @@ -703,18 +700,12 @@ "delete-chat-title": "Möchten Sie '{{name}}' wirklich löschen?", "delete-chat-text": "Alle Chatnachrichten gehen verloren", "delete-chat-confirm": "Ja, löschen", - "action-approval-required": "Genehmigung der Aktion erforderlich", "approve": "Genehmigen", - "approve-all": "Alle weiteren Aktionen genehmigen", "deny": "Ablehnen", - "processing": "Wird verarbeitet...", "approved": "Fertig", - "denied": "Abgelehnt", "error": "Fehlgeschlagen", "thinking": "Denke nach...", - "rename-chat-title": "Diesen Chat umbenennen", - "export-chat": "Chat exportieren", - "main-title": "Hallo! Ich bin Ihr KI-Assistent" + "export-chat": "Chat exportieren" }, "alarm": { "alarm": "Alarm", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Ziehen Sie Ihre Kontozugangsdaten-Datei hierher" }, "solution-creator": { - "ai-solution-creator": "KI-Lösungsersteller", "describe-solution-you-want": "Beschreiben Sie die Lösung, die Sie erstellen möchten", - "enter-your-prompt": "Prompt eingeben", "target": "Ziel", "install-solution": "Installieren", - "solution-overview": "Lösungsübersicht: {{ name }}", - "dashboards-overview": "Dashboards-Übersicht: {{ name }}", - "entity-profile": "Entitätsprofil", - "entity-profiles": "Entitätsprofile", - "name": "Name", - "iam": "IAM", - "iam-full": "Identitäts- und Zugriffsverwaltung", - "table-view": "Tabelle", - "schema-view": "Schema", - "iam-info": "IAM-Info", "operation": { "C": "Erstellen", "R": "Lesen", "U": "Speichern", "D": "Löschen" }, - "alarm-info": "Alarm-Info", "description": "Beschreibung", - "data": "Daten", - "entity-info": "Entitäts-Info", - "calculated-field-info": "Info zum berechneten Feld", - "field-type": "Feldtyp", - "scope": "Bereich", "delete-alarm-title": "Diesen vorgeschlagenen Alarm löschen?", "delete-alarm-text": "Dieser Alarm, der auf Grundlage Ihrer Beschreibung vorgeschlagen wurde, wird nicht in die vorgeschlagene Lösung aufgenommen.
Sie können Alarme später jederzeit manuell bearbeiten oder neu erstellen. Diese Aktion kann nicht rückgängig gemacht werden.", - "basic-mode": "Einfach", - "advanced-mode": "Erweitert", "create-solution": "Lösung erstellen", "go-dashboard-manager": "Weiter: Dashboard-Design", - "success-generate-title": "Lösung ist bereit!", - "success-generate-sub-title": "Sie können sie über die Schaltfläche unten in Ihrem Konto installieren", - "success-generate-install-title": "Lösung installiert!", - "success-generate-install-sub-title": "Um die Lösung zu bearbeiten, deinstallieren Sie bitte zuerst die vorhandene Instanz", - "main-title": "Hallo! Ich bin Ihr KI-Assistent", - "sub-title": "Ich helfe Ihnen, Ihre Anforderungen in eine voll funktionsfähige IoT-Lösung zu verwandeln.\nBeschreiben Sie einfach, was Sie erreichen möchten, und ich erledige den Rest.", - "solutions": "Lösungen", "new-solution": "Neue Lösung", "uninstall-solution": "Deinstallieren", "uninstall-solution-dialog-title": "Möchten Sie ‘{{ name }}’ wirklich deinstallieren?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Alle Ihre Daten gehen verloren", "delete-solution-confirm": "Ja, löschen", "copy-solution": "Lösung kopieren", - "expand-sidebar": "Seitenleiste ausklappen", - "collapse-sidebar": "Seitenleiste einklappen", "solution-id": "Lösungs-ID", "solution-id-required": "Lösungs-ID ist erforderlich", - "rename-solution-title": "Diese Lösung umbenennen", - "generate-again": "Erneut generieren", "skip-interview": "Interview überspringen", "update-solution": "Lösung aktualisieren", "finish-edit": "Bearbeitung abschließen", @@ -11298,8 +11258,6 @@ "water-metering": "Wasserzählung", "coffee-machine-monitoring": "Kaffeemaschinen-Überwachung", "fleet-geofencing": "Flotten-Geofencing", - "more-examples": "Weitere Beispiele", - "hide": "Ausblenden", "solution-info": "Lösungsinfo", "solution-info-with-name": "Lösungsinfo: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Haupt-Dashboard", "view-as": "Anzeigen als {{ name }}", - "generated-by-calculated-field-name": "Erzeugt durch berechnetes Feld ‘{{ name }}’", "estimate-wait-time": "Geschätzte Wartezeit ca. {{ time }}", - "analyzing-your-request": "Anfrage wird analysiert...", "condition": "Bedingung", - "installing": "Lösung wird installiert...", - "step-architecture-design": "Architekturentwurf", - "step-dashboard-design": "Dashboard-Entwurf", - "step-solution-installation": "Lösungsinstallation", "step-reading-device-data": "Gerätedaten werden gelesen…", "step-analyzing-telemetry-attributes": "Telemetrie und Attribute werden analysiert…", "step-selecting-widgets": "Widgets für Ihre Daten werden ausgewählt…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarmregeln werden erstellt…", "step-loading-assembling-dashboards": "Dashboards werden zusammengestellt…", "step-loading-preparing-states": "Zustände werden vorbereitet…", - "step-loading-initializing-solution": "Lösung wird initialisiert…", - "ai-credits": "KI-Credits", - "ai-credits-update": "Speichern", - "ai-credits-usage": "KI-Credits: {{ used }} von {{ max }} verbraucht", - "ai-credits-description": "Sie haben diesen Monat {{ used }} von {{ max }} AI Credits verbraucht. Das Limit wird am {{ date }} zurückgesetzt. Um Ihr AI-Credit-Kontingent zu erhöhen, wenden Sie sich bitte an Ihren Systemadministrator." + "step-loading-initializing-solution": "Lösung wird initialisiert…" }, "markdown": { "edit": "Bearbeiten", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Wenig Festplattenspeicher. Bereinigen oder erweitern Sie den Speicherplatz, um Datenverlust zu vermeiden.", "disk-critical-text": "Kritisch wenig Festplattenspeicher. Bereinigen oder erweitern Sie den Speicherplatz, um Datenverlust zu vermeiden." }, - "cluster-info": { - "service-id": "Dienst-ID", - "service-type": "Diensttyp", - "no-data": "Keine Daten" - }, "transport-messages": { "title": "Transportnachrichten", "info": "Alle Nachrichten, die von Geräten empfangen wurden" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Noch keine zuletzt angesehenen Dashboards" }, "configured-features": { - "title": "Konfigurierte Funktionen", - "info": "Status der Funktionen, die eine Konfiguration erfordern", - "white-labeling-feature": "White-Labeling", - "email-feature": "E-Mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funktion ist konfiguriert.\nZum Einrichten klicken", "feature-not-configured": "Funktion ist nicht konfiguriert.\nZum Einrichten klicken" }, - "version-info": { - "title": "Version", - "contact-us": "Kontaktieren Sie uns", - "current-version": "Aktuelle Version", - "current": "Aktuell", - "available-version": "Verfügbare Version", - "available": "Verfügbar", - "upgrade": "Upgrade durchführen", - "version-is-up-to-date": "Version ist aktuell" - }, - "license-info": { - "title": "Lizenzinformationen", - "view-all": "Alle anzeigen", - "license-portal": "Lizenzportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Geräte", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrationen", - "community-support": "Community-Support", - "white-labeling": "White-Labeling", - "unlimited-datapoints-and-messages": "Unbegrenzte Datenpunkte und Nachrichten", - "unlimited-api-calls": "Unbegrenzte API-Aufrufe" - }, "usage-info": { "title": "Nutzung", "entities": "Entitäten", diff --git a/ui-ngx/src/assets/locale/locale.constant-el_GR.json b/ui-ngx/src/assets/locale/locale.constant-el_GR.json index bc7726c070..2e7d5f6b36 100644 --- a/ui-ngx/src/assets/locale/locale.constant-el_GR.json +++ b/ui-ngx/src/assets/locale/locale.constant-el_GR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Διαμόρφωση με τη βοήθεια AI", - "follow-up-prompt-placeholder": "Απάντηση...", - "sub-title": "Μπορώ να σας βοηθήσω να ρυθμίσετε και να διαχειριστείτε τις συσκευές, τους πίνακες ελέγχου, τα υπολογιζόμενα πεδία, τους κανόνες συναγερμών και τις ειδοποιήσεις σας — απλώς περιγράψτε τι χρειάζεστε και θα αναλάβω τα υπόλοιπα.", "new-chat": "Νέα συνομιλία", - "no-chats": "Δεν υπάρχουν ακόμη συνομιλίες", "today": "Σήμερα", "yesterday": "Χθες", "last-7-days": "Τελευταίες 7 ημέρες", @@ -703,20 +700,12 @@ "delete-chat-title": "Είστε βέβαιοι ότι θέλετε να διαγράψετε το '{{name}}';", "delete-chat-text": "Όλα τα μηνύματα της συνομιλίας θα χαθούν", "delete-chat-confirm": "Ναι, διαγραφή", - "action-approval-required": "Απαιτείται έγκριση ενέργειας", "approve": "Έγκριση", - "approve-all": "Έγκριση όλων των επόμενων ενεργειών", "deny": "Απόρριψη", - "processing": "Επεξεργασία...", "approved": "Ολοκληρώθηκε", - "denied": "Απορρίφθηκε", "error": "Απέτυχε", "thinking": "Σκέφτομαι...", - "connection-lost": "Η σύνδεση με τον βοηθό AI χάθηκε. Επανασύνδεση...", - "reconnect-failed": "Δεν ήταν δυνατή η επανασύνδεση με τον βοηθό AI. Ανοίξτε ξανά τη συνομιλία για να δείτε την απάντησή του.", - "rename-chat-title": "Μετονομασία αυτής της συνομιλίας", - "export-chat": "Εξαγωγή συνομιλίας", - "main-title": "Γεια σας! Είμαι ο βοηθός AI σας" + "export-chat": "Εξαγωγή συνομιλίας" }, "alarm": { "alarm": "Συναγερμός", @@ -11247,47 +11236,20 @@ "select-recaptcha-enterprise-service-account-file": "Σύρετε και αποθέστε το αρχείο διαπιστευτηρίων του λογαριασμού σας" }, "solution-creator": { - "ai-solution-creator": "Δημιουργός λύσεων AI", "describe-solution-you-want": "Περιγράψτε τη λύση που θέλετε να δημιουργήσετε", - "enter-your-prompt": "Εισαγάγετε την προτροπή σας", "target": "Στόχος", "install-solution": "Εγκατάσταση", - "solution-overview": "Επισκόπηση λύσης: {{ name }}", - "dashboards-overview": "Επισκόπηση πινάκων ελέγχου: {{ name }}", - "entity-profile": "Προφίλ οντότητας", - "entity-profiles": "Προφίλ οντοτήτων", - "name": "Όνομα", - "iam": "IAM", - "iam-full": "Διαχείριση ταυτοτήτων και πρόσβασης", - "table-view": "Πίνακας", - "schema-view": "Σχήμα", - "iam-info": "Πληροφορίες IAM", "operation": { "C": "Δημιουργία", "R": "Ανάγνωση", "U": "Ενημέρωση", "D": "Διαγραφή" }, - "alarm-info": "Πληροφορίες συναγερμού", "description": "Περιγραφή", - "data": "Δεδομένα", - "entity-info": "Πληροφορίες οντότητας", - "calculated-field-info": "Πληροφορίες υπολογιζόμενου πεδίου", - "field-type": "Τύπος πεδίου", - "scope": "Εμβέλεια", "delete-alarm-title": "Διαγραφή αυτού του προτεινόμενου συναγερμού;", "delete-alarm-text": "Αυτός ο συναγερμός, που προτάθηκε με βάση την περιγραφή σας, δεν θα προστεθεί στη δημιουργία της προτεινόμενης λύσης.
Μπορείτε πάντα να επεξεργαστείτε ή να δημιουργήσετε ξανά συναγερμούς χειροκίνητα αργότερα. Αυτή η ενέργεια δεν μπορεί να αναιρεθεί.", - "basic-mode": "Βασική", - "advanced-mode": "Για προχωρημένους", "create-solution": "Δημιουργία λύσης", "go-dashboard-manager": "Επόμενο: Σχεδίαση πίνακα ελέγχου", - "success-generate-title": "Η λύση είναι έτοιμη!", - "success-generate-sub-title": "Μπορείτε να την εγκαταστήσετε στον λογαριασμό σας κάνοντας κλικ στο παρακάτω κουμπί", - "success-generate-install-title": "Η λύση εγκαταστάθηκε!", - "success-generate-install-sub-title": "Για να επεξεργαστείτε τη λύση, απεγκαταστήστε πρώτα την υπάρχουσα εγκατάσταση", - "main-title": "Γεια σας! Είμαι ο βοηθός AI σας", - "sub-title": "Σας βοηθώ να μετατρέψετε τις απαιτήσεις σας σε μια πλήρως λειτουργική λύση IoT.\nΑρκεί να περιγράψετε τι θέλετε να επιτύχετε και θα αναλάβω τα υπόλοιπα.", - "solutions": "Λύσεις", "new-solution": "Νέα λύση", "uninstall-solution": "Απεγκατάσταση", "uninstall-solution-dialog-title": "Είστε βέβαιοι ότι θέλετε να απεγκαταστήσετε τη λύση ‘{{ name }}’;", @@ -11297,12 +11259,8 @@ "delete-solution-text": "Όλα τα δεδομένα σας θα χαθούν", "delete-solution-confirm": "Ναι, διαγραφή", "copy-solution": "Αντιγραφή λύσης", - "expand-sidebar": "Ανάπτυξη πλευρικής γραμμής", - "collapse-sidebar": "Σύμπτυξη πλευρικής γραμμής", "solution-id": "ID λύσης", "solution-id-required": "Απαιτείται ID λύσης", - "rename-solution-title": "Μετονομασία αυτής της λύσης", - "generate-again": "Νέα δημιουργία", "skip-interview": "Παράλειψη συνέντευξης", "update-solution": "Ενημέρωση λύσης", "finish-edit": "Ολοκλήρωση επεξεργασίας", @@ -11312,8 +11270,6 @@ "water-metering": "Μέτρηση νερού", "coffee-machine-monitoring": "Παρακολούθηση μηχανής καφέ", "fleet-geofencing": "Γεωπερίφραξη στόλου", - "more-examples": "Περισσότερα παραδείγματα", - "hide": "Απόκρυψη", "solution-info": "Πληροφορίες λύσης", "solution-info-with-name": "Πληροφορίες λύσης: {{ name }}", "status": "Κατάσταση", @@ -11326,14 +11282,8 @@ "info": "Πληροφορίες", "main-dashboard": "Κύριος πίνακας ελέγχου", "view-as": "Προβολή ως {{ name }}", - "generated-by-calculated-field-name": "Δημιουργήθηκε από το υπολογιζόμενο πεδίο ‘{{ name }}’", "estimate-wait-time": "Ο εκτιμώμενος χρόνος αναμονής είναι ~{{ time }}", - "analyzing-your-request": "Ανάλυση του αιτήματός σας...", "condition": "Συνθήκη", - "installing": "Εγκατάσταση λύσης...", - "step-architecture-design": "Σχεδιασμός αρχιτεκτονικής", - "step-dashboard-design": "Σχεδιασμός πίνακα ελέγχου", - "step-solution-installation": "Εγκατάσταση λύσης", "step-reading-device-data": "Ανάγνωση δεδομένων συσκευής…", "step-analyzing-telemetry-attributes": "Ανάλυση τηλεμετρίας και χαρακτηριστικών…", "step-selecting-widgets": "Επιλογή widget για τα δεδομένα σας…", @@ -11365,11 +11315,7 @@ "step-loading-building-alarm-rules": "Δημιουργία κανόνων συναγερμών…", "step-loading-assembling-dashboards": "Συναρμολόγηση πινάκων ελέγχου…", "step-loading-preparing-states": "Προετοιμασία καταστάσεων…", - "step-loading-initializing-solution": "Αρχικοποίηση λύσης…", - "ai-credits": "Πιστώσεις AI", - "ai-credits-update": "Αλλαγή προγράμματος", - "ai-credits-usage": "Πιστώσεις AI: χρησιμοποιήθηκαν {{ used }} από {{ max }}", - "ai-credits-description": "Έχετε χρησιμοποιήσει {{ used }} από τις {{ max }} πιστώσεις AI σας αυτόν τον μήνα. Το όριο μηδενίζεται στις {{ date }}. Για να αυξήσετε το διαθέσιμο όριο πιστώσεων AI, επικοινωνήστε με τον διαχειριστή του συστήματός σας." + "step-loading-initializing-solution": "Αρχικοποίηση λύσης…" }, "markdown": { "edit": "Επεξεργασία", @@ -13795,11 +13741,6 @@ "disk-warning-text": "Ο χώρος στον δίσκο είναι χαμηλός. Για να αποφύγετε την απώλεια δεδομένων, ελευθερώστε ή επεκτείνετε τον χώρο στον δίσκο.", "disk-critical-text": "Κρίσιμα χαμηλός χώρος στον δίσκο. Για να αποφύγετε την απώλεια δεδομένων, ελευθερώστε ή επεκτείνετε τον χώρο στον δίσκο." }, - "cluster-info": { - "service-id": "Αναγνωριστικό υπηρεσίας", - "service-type": "Τύπος υπηρεσίας", - "no-data": "Δεν υπάρχουν δεδομένα" - }, "transport-messages": { "title": "Μηνύματα μεταφοράς", "info": "Όλα τα μηνύματα που ελήφθησαν από συσκευές" @@ -13838,41 +13779,9 @@ "no-last-viewed-dashboards": "Δεν έχετε προβάλει ακόμη πίνακες ελέγχου" }, "configured-features": { - "title": "Διαμορφωμένες δυνατότητες", - "info": "Κατάσταση δυνατοτήτων που απαιτούν ρύθμιση", - "white-labeling-feature": "White labeling", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Η δυνατότητα έχει ρυθμιστεί.\nΚάντε κλικ για ρύθμιση", "feature-not-configured": "Η δυνατότητα δεν έχει ρυθμιστεί.\nΚάντε κλικ για ρύθμιση" }, - "version-info": { - "title": "Έκδοση", - "contact-us": "Επικοινωνήστε μαζί μας", - "current-version": "Τρέχουσα έκδοση", - "current": "Τρέχουσα", - "available-version": "Διαθέσιμη έκδοση", - "available": "Διαθέσιμη", - "upgrade": "Αναβάθμιση", - "version-is-up-to-date": "Η έκδοση είναι ενημερωμένη" - }, - "license-info": { - "title": "Πληροφορίες άδειας χρήσης", - "view-all": "Προβολή όλων", - "license-portal": "Πύλη αδειών χρήσης", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Συσκευές", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Περιουσιακά στοιχεία", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Πίνακες ελέγχου", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Ενσωματώσεις", - "community-support": "Υποστήριξη κοινότητας", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Απεριόριστα σημεία δεδομένων και μηνύματα", - "unlimited-api-calls": "Απεριόριστες κλήσεις API" - }, "usage-info": { "title": "Χρήση", "entities": "Οντότητες", diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 7d7317dae7..886d065747 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -691,11 +691,42 @@ "use-system-mobile-settings": "Use system mobile settings" }, "ai-assistant": { + "question": { + "other-chip": "Other…", + "other-color": "Other color…", + "pick-color": "Pick a color", + "needs-answer": "Needs an answer", + "count": "{{at}} of {{of}}", + "other": "Something else", + "other-hint": "type your answer", + "next": "Next", + "done": "Done", + "skip": "Skip", + "you-said": "You said", + "none": "None", + "no-answer": "No answer", + "your-answer": "Your answer", + "type-answer": "Type the answer", + "type-secret": "Paste it here; it stays hidden" + }, + "ai-assistant": "AI Assistant", "configure-with-ai": "Configure with AI", - "follow-up-prompt-placeholder": "Reply...", - "sub-title": "I can help you set up and manage your Devices, Dashboards, Calculated Fields, Alarm Rules, and Notifications — just describe what you need, and I'll handle the rest.", + "follow-up-prompt-placeholder": "Add something, or ask what happened…", + "split-view": "Split view", + "loading-chat": "Opening the chat…", + "ai-assistant-cue": "AI Assistant · {{ cue }}", + "keys": { + "title": "Keyboard shortcuts", + "composer": "Composer", + "chat": "Chat", + "stop": "Stop the agent", + "slash": "Go to the composer, or open the chat beside a page", + "search-chats": "Search chats", + "find": "Find in an open file", + "close-panel": "Close the panel beside the chat" + }, + "back-to-panel": "Back to the panel", "new-chat": "New chat", - "no-chats": "No chats yet", "today": "Today", "yesterday": "Yesterday", "last-7-days": "Last 7 days", @@ -703,17 +734,21 @@ "delete-chat-title": "Are you sure you want to delete '{{name}}'?", "delete-chat-text": "All chat messages will be lost", "delete-chat-confirm": "Yes, delete", - "action-approval-required": "Action approval required", "approve": "Approve", - "approve-all": "Approve all further actions", "deny": "Deny", - "processing": "Processing...", "approved": "Done", - "denied": "Denied", "error": "Failed", "thinking": "Thinking...", - "connection-lost": "Connection to the AI Assistant was lost. Reconnecting...", - "reconnect-failed": "Couldn't reconnect to the AI Assistant. Reopen the chat to see its reply.", + "stopped-after": "{ count, plural, =1 {You stopped this reply after 1 step. Nothing more was done.} other {You stopped this reply after # steps. Nothing more was done.} }", + "stopped-before": "You stopped this reply before any step. Nothing was done.", + "notice": { + "connection-lost": "The connection to the AI service is lost. Reconnecting…", + "connection-failed": "The connection to the AI service is lost. Send the message again to retry.", + "connected-again": "Connected again. The run picks up where it stopped.", + "reconnect-failed": "Could not reconnect. Send the message again to retry.", + "rate-limited": "Too many requests for a moment. Send the message again in a minute.", + "credits-used-up": "The AI credits are used up. Sending resumes when the limit resets." + }, "ask-the-assistant": "Ask the AI Assistant", "send": "Send", "new-line": "New line", @@ -730,6 +765,2191 @@ "attachment-larger-than": "Larger than {{size}}", "attachment-svg-failed": "This SVG can't be converted to an image", "attachment-over-limit": "More than {{count}} files", + "detail": { + "check-dashboard-access": "Checked what {{customer}} can see on {{dashboard}}", + "notification-status": { + "sent": "Sent", + "scheduled": "Scheduled", + "processing": "Sending" + }, + "not-visible": "{{count}} not visible to the customer", + "all-visible": "The customer can see every entity this dashboard shows.", + "state-aliases": "Resolved only when the dashboard opens: {{aliases}}", + "access-truncated": "Only the first 50 entities were checked.", + "user-groups": "User groups", + "grants": "Roles it gives", + "members": "Members", + "shared-with": "Shared with", + "roles": "Roles", + "user-error": "The user was not created: {{reason}}", + "activation-email": "Activation email sent", + "iot-hub-query": "Executed '{{query}}' query against IoT Hub", + "iot-hub-browse": "Browsed IoT Hub", + "iot-hub-installed": "Listed the items installed from IoT Hub", + "iot-hub-read": "Read '{{name}}' in IoT Hub", + "search": "Searched {{what}}", + "search-one": "Looked up {{entity}}", + "search-related-from": "Searched {{what}} that {{entity}} points to", + "search-related-to": "Searched {{what}} pointing to {{entity}}", + "search-named": "Searched {{what}} named like '{{name}}'", + "search-typed": "Searched {{what}} of the {{types}} profile", + "search-text": "Searched {{what}} matching '{{text}}'", + "search-alarms-of": "Searched the alarms of {{entity}}", + "what": { + "devices": "devices", + "assets": "assets", + "devices-assets": "devices and assets", + "entity-views": "entity views", + "edges": "edges", + "customers": "customers", + "users": "users", + "dashboards": "dashboards", + "tenants": "tenants", + "device-profiles": "device profiles", + "asset-profiles": "asset profiles", + "groups": "entity groups", + "gateways": "gateways", + "alarms": "alarms", + "alarm-rules": "alarm rules", + "calculated-fields": "calculated fields", + "notification-targets": "notification recipients", + "notification-templates": "notification templates", + "notification-rules": "notification rules", + "images": "images", + "entities": "entities" + }, + "what-found": { + "devices": "Devices", + "assets": "Assets", + "entity-views": "Entity views", + "edges": "Edges", + "customers": "Customers", + "users": "Users", + "dashboards": "Dashboards", + "tenants": "Tenants", + "device-profiles": "Device profiles", + "asset-profiles": "Asset profiles", + "groups": "Entity groups", + "entities": "Entities" + }, + "read-entity": "Read {{entity}}", + "read-relations": "Read the relations of {{entity}}", + "relation-from": "{{type}}, from it", + "relation-to": "{{type}}, to it", + "read-latest": "Read the latest values of {{entity}}", + "read-latest-keys": "Read the latest {{keys}} of {{entity}}", + "read-history": "Read the history of {{entity}}, {{from}} – {{to}}", + "read-history-keys": "Read the history of {{keys}} on {{entity}}, {{from}} – {{to}}", + "read-keys": "Listed the telemetry keys of {{entity}} with their latest values", + "read-attributes": "Read the attributes of {{entity}}", + "read-attributes-scope": "Read the {{scope}} of {{entity}}", + "discover-attribute-keys": "Listed the attribute keys used by the devices of {{entity}}", + "delete-attributes": "Deleted {{scope}} from {{entity}}", + "scope": { + "server": "server attributes", + "shared": "shared attributes", + "client": "client attributes", + "other": "attributes" + }, + "read-credentials": "Read the credentials of {{entity}}", + "read-endpoints": "Read the platform's connection settings", + "read-api-usage": "Read the API usage", + "read-audit-logs": "Read the audit log", + "read-audit-logs-of": "Read the audit log of {{entity}}", + "read-tasks": "Read the task manager", + "save-image": "Added image {{name}} to the image gallery", + "update-alarms": { + "acknowledge": "{ count, plural, =1 {Acknowledged an alarm} other {Acknowledged # alarms} }", + "clear": "{ count, plural, =1 {Cleared an alarm} other {Cleared # alarms} }", + "assign": "{ count, plural, =1 {Assigned an alarm} other {Assigned # alarms} }", + "unassign": "{ count, plural, =1 {Unassigned an alarm} other {Unassigned # alarms} }", + "comment": "{ count, plural, =1 {Commented on an alarm} other {Commented on # alarms} }", + "other": "{ count, plural, =1 {Updated an alarm} other {Updated # alarms} }" + }, + "alarms-done": "Done", + "alarms-skipped": "Already in that state", + "alarms-failed": "Failed", + "save-relations": "Changed relations", + "relations-added": "Added", + "relations-removed": "Removed", + "relations-failed": "Failed", + "read-versions": "Read the saved versions", + "read-gateway-status": "Checked gateway {{name}}", + "gateway-online": "Online", + "gateway-offline": "Offline", + "gateway-connectors": "Connectors", + "read-ota": "{ count, plural, =1 {Checked the update of one device} other {Checked the update of # devices} }", + "read-ota-packages": "Read the OTA packages", + "read-edges": "Read the edges", + "read-edge": "Read the edge {{name}}", + "edge-assigned": "Assigned to the edge", + "read-edge-events": "Read the edge's downlinks", + "read-edge-install-instructions": "Read the edge install instructions", + "read-edge-upgrade-instructions": "Read the edge upgrade instructions", + "create-edge": "Create the edge {{name}}", + "update-edge": "Update the edge", + "assign-to-edge": "Change what the edge receives", + "edge-missing-rule-chains": "Rule chains the edge is missing", + "sync-edge": "Sync the edge", + "read-rule-chain-templates": "Read the edge rule chains", + "read-rule-chain-template": "Read the edge rule chain {{name}}", + "rule-chain-template-root": "Root rule chain of new edges", + "rule-chain-template-auto": "Assigned to new edges", + "rule-chain-template-edges": "Assigned to edges", + "rule-chain-template-nodes": "Rule nodes", + "set-rule-chain-template": "Change how the rule chain reaches new edges", + "read-agents": "Read the agents", + "read-agent": "Read {{name}}", + "agent-applications": "Applications", + "agent-units": "Units", + "agent-operations": "Recent operations", + "read-agent-instructions": "Read the agent install command", + "read-agent-profiles": "Read the agent profiles", + "create-agent": "Create the agent {{name}}", + "update-agent": "Update the agent", + "install-agent-application": "Install an application on the agent", + "run-agent-operation": "Run an operation on the agent", + "save-agent-profile": "Save the agent profile", + "save-agent-app-profile": "Save the application profile", + "run-agent-bulk-action": "Run a bulk action", + "wait-agent-operation": "Followed the agent operation", + "read-white-labeling": "Read the white labeling", + "read-website-brand": "Read the brand of {{site}}", + "website-colors": "Colors", + "website-logos": "Logo candidates", + "image-logo": "Logo", + "image-collapsed-logo": "Collapsed logo", + "image-favicon": "Favicon", + "website-not-read": "The site blocked automated reading, so only its icon was read", + "save-white-labeling": "Changed the platform's white labeling", + "save-white-labeling-login": "Changed the login page's white labeling", + "read-mail-templates": "Read the mail templates", + "read-mail-template": "Read the {{template}} email", + "mail-system-in-use": "The platform's own templates are in use", + "mail-own-in-use": "The tenant's own templates are in use", + "save-mail-template": "Changed the {{template}} email", + "save-mail-templates": "Changed the emails", + "mail-use-system": "Went back to the platform's own mail templates", + "mail-replaced": "Replaced", + "read-custom-translation": "Read the custom translation {{locale}}", + "translation-matches": "Found texts", + "translation-customized": "Customized texts", + "save-custom-translation": "Changed texts of {{locale}}", + "translation-set": "Changed", + "translation-removed": "Back to the platform's text", + "read-custom-menus": "Read the custom menus", + "read-security-settings": "Read the security settings", + "read-mobile-center": "Read the mobile center", + "read-scheduler-events": "Read the scheduler", + "create-report-template": "Created the report template {{name}}", + "update-report-template": "Changed the report template", + "read-report-template": "Read the layout of '{{name}}'", + "read-report-component": "Read the component {{path}} of '{{name}}'", + "sub-report": "Sub-report", + "report-components": "Components", + "report-problems": "Problems", + "add-report-components": "Added report components", + "update-report-component": "Changed the component {{path}}", + "move-report-component": "Moved {{path}} to {{target}}", + "save-report-alias": "Saved the entity alias {{name}}", + "save-report-filter": "Saved the filter {{name}}", + "test-report-template": "Checked the report", + "report-pages": "{ count, plural, =1 {1 page} other {# pages} }", + "report-rows": "{ count, plural, =1 {1 row} other {# rows} }", + "report-pages-clean": "{ count, plural, =1 {1 page} other {# pages} }, no errors", + "report-rows-clean": "{ count, plural, =1 {1 row} other {# rows} }, no errors", + "report-errors": "Errors", + "save-two-factor-settings": "Changed the two-factor authentication settings", + "save-oauth2-domain": "Changed OAuth 2.0 sign-in on the domain", + "read-my-account": "Read your account", + "read-mail-server": "Read the mail server", + "save-mail-server": "Changed the mail server", + "save-my-profile": "Changed your profile", + "save-my-two-factor": "Changed your two-factor methods", + "update-api-key": "Changed the API key", + "delete-api-key": "Deleted the API key", + "read-scheduler-event": "Read the scheduler event {{name}}", + "no-scheduler-events": "No scheduler events yet.", + "save-scheduler-event": "Changed the scheduler event", + "create-scheduler-event": "Created the scheduler event {{name}}", + "read-reports": "Read the reports", + "read-report-templates": "Read the report templates", + "no-report-templates": "No report templates", + "read-scheduled-reports": "Read the scheduled reports", + "read-generated-reports": "Read the generated reports", + "no-scheduled-reports": "No scheduled reports", + "no-generated-reports": "No generated reports", + "attach-report": "Attached {{name}}", + "read-scheduled-report": "Read the scheduled report {{name}}", + "save-scheduled-report": "Changed the scheduled report", + "create-scheduled-report": "Scheduled the report {{name}}", + "generate-report": "Generated the report", + "report-still-running": "Still generating; it will appear on the Reports page", + "mobile-apps": "Apps", + "no-mobile-apps": "No mobile apps yet.", + "no-mobile-bundles": "No mobile bundles yet, so the apps show the standard menu.", + "save-mobile-app": "Changed the mobile app", + "register-mobile-app": "Registered the mobile app {{name}}", + "save-mobile-bundle": "Changed the mobile bundle", + "create-mobile-bundle": "Created the mobile bundle {{name}}", + "read-widgets": "Read the widgets", + "read-widgets-bundles": "Read the widgets bundles", + "read-widgets-bundle": "Read the widgets bundle {{name}}", + "no-widgets": "No widgets", + "no-widgets-bundles": "No widgets bundles", + "read-widget-type": "Read the widget {{name}}", + "read-widget-parts": "Read the {{parts}} of '{{name}}'", + "widget-problems": "Problems", + "read-scada-symbols": "Read the SCADA symbols", + "read-scada-symbol": "Read the SCADA symbol {{name}}", + "read-scada-symbol-parts": "Read the {{parts}} of '{{name}}'", + "no-scada-symbols": "No SCADA symbols", + "create-scada-symbol": "Drew the SCADA symbol {{name}}", + "update-scada-symbol": "Redrew the SCADA symbol {{name}}", + "copy-scada-symbol": "Copied the SCADA symbol as {{name}}", + "change-scada-symbol": "Changed the SCADA symbol {{name}}", + "check-scada-symbol": "Ran the SCADA symbol", + "create-scada-symbol-widget": "Added {{name}} to the widgets library", + "scada-symbol-check-clean": "Rendered without errors", + "scada-symbol-check-not-rendered": "The symbol did not render", + "scada-symbol-behaviors": "Behaviors", + "scada-symbol-problems": "Problems", + "create-widget": "Created the widget {{name}}", + "update-widget-type": "Changed the widget", + "update-widget-edits": "Changed the widget: { count, plural, =1 {1 edit} other {# edits} }", + "widget-warnings": "Warnings", + "check-widget": "Ran the widget in the preview", + "widget-check-errors": "{ count, plural, =1 {1 error} other {# errors} }", + "widget-check-clean": "Ran without errors", + "widget-check-not-run": "The widget did not start", + "widget-errors": "Errors", + "widget-console": "Console errors", + "save-widgets-bundle": "Changed the widgets bundle", + "create-widgets-bundle": "Created the widgets bundle {{name}}", + "widgets": "Widgets", + "save-mobile-qr-code": "Changed the mobile app QR code", + "mobile-bundle-menu": "Menu of {{name}}", + "read-custom-menu": "Read the menu {{name}}", + "save-custom-menu": "Changed the custom menu", + "create-custom-menu": "Created the custom menu {{name}}", + "menu-changes": "Changes", + "reset-white-labeling": "Reset the platform's white labeling to the defaults", + "reset-white-labeling-login": "Reset the login page's white labeling to the defaults", + "save-ota-package": "Created the OTA package {{name}}", + "assign-ota-package": "Assigned the OTA package", + "clear-ota-package": "Cleared the OTA package", + "commit-version": "Saved the version '{{name}}'", + "restore-version": "Restored from version {{version}}", + "read-platform-settings": "Read the platform settings", + "save-platform-settings": "Saved the platform settings", + "usage": { + "devices": "Devices", + "assets": "Assets", + "customers": "Customers", + "users": "Users", + "dashboards": "Dashboards", + "edges": "Edges", + "transportMessages": "Transport messages this month", + "transportDataPoints": "Transport data points this month", + "ruleEngineExecutions": "Rule engine executions this month", + "javaScriptExecutions": "JavaScript executions this month", + "tbelExecutions": "TBEL executions this month", + "storedDataPoints": "Stored data points this month", + "createdAlarms": "Alarms created this month", + "emails": "Emails this month", + "sms": "SMS this month", + "aiCredits": "AI credits this month", + "generatedReports": "Reports generated this month", + "limited": "{ count, plural, =1 {One limit is close to or at its maximum.} other {# limits are close to or at their maximum.} }" + }, + "read-connect-commands": "Read the commands that connect {{entity}}", + "research": "Researched how {{device}} connects", + "research-question": "Researched {{device}}: {{question}}", + "search-web": "Searched the web for '{{query}}'", + "fetch-page": "Read {{url}}", + "create-dashboard": "Created the dashboard '{{name}}'", + "update-dashboard": "Updated {{entity}}", + "read-dashboard": "Read the layout of {{entity}}", + "add-state": "Added the state '{{name}}' to {{entity}}", + "update-state": "Updated the state '{{state}}' of {{entity}}", + "add-alias": "Added the entity alias '{{name}}' to {{entity}}", + "update-alias": "Updated the entity alias '{{name}}' of {{entity}}", + "read-alias": "Read the entity alias '{{name}}'", + "add-filter": "Added the filter '{{name}}' to {{entity}}", + "update-filter": "Updated the filter '{{name}}' of {{entity}}", + "read-filter": "Read the filter '{{name}}'", + "add-widget": "Added a widget to {{entity}}", + "add-widgets": "Added {{count}} widgets to {{entity}}", + "add-scada-connectors": "Drew {{count}} pipe lines on {{entity}}", + "update-widget": "Updated the widget '{{name}}' of {{entity}}", + "read-widget": "Read the widget '{{name}}'", + "place-widgets": "Placed {count} { count, plural, =1 {widget} other {widgets} } on {entity}", + "save-attributes": { + "server": "Saved {count} { count, plural, =1 {server attribute} other {server attributes} } on {entity}", + "shared": "Saved {count} { count, plural, =1 {shared attribute} other {shared attributes} } on {entity}", + "client": "Saved {count} { count, plural, =1 {client attribute} other {client attributes} } on {entity}", + "other": "Saved {count} { count, plural, =1 {attribute} other {attributes} } on {entity}" + }, + "widget-size": "{{width}} × {{height}}", + "widget-size-at": "{{width}} × {{height}} at {{col}}, {{row}}", + "widget-placed": "{{name}} · {{width}} × {{height}} at {{col}}, {{row}}", + "set-html-page": "Had the state '{{state}}' of {{entity}} written as an HTML page", + "read-html-page": "Read the HTML page of the state '{{state}}' of {{entity}}", + "delete": "Deleted {{entity}}", + "create-device": "Created the device '{{name}}'", + "update-device": "Updated the device '{{name}}'", + "save": "Saved the {{what}} '{{name}}'", + "kind": { + "calculated-field": "calculated field", + "entity-view": "entity view", + "asset": "asset", + "asset-profile": "asset profile", + "secret": "secret", + "ai-model": "AI model", + "resource": "resource", + "alarm-rule": "alarm rule", + "notification-target": "notification recipients", + "notification-template": "notification template", + "notification-rule": "notification rule" + }, + "reprocess": "Recalculated {{entity}}, {{from}} – {{to}}", + "this": "this {{what}}", + "thing": { + "widget": "widget", + "state": "state", + "alias": "entity alias", + "filter": "filter", + "alarm-rule": "alarm rule", + "calculated-field": "calculated field", + "notification-rule": "notification rule", + "notification-target": "recipient list", + "notification-template": "notification template", + "entity": "entity", + "tenant": "tenant", + "tenant-profile": "tenant profile", + "customer": "customer", + "user": "user", + "device": "device", + "device-profile": "device profile", + "asset-profile": "asset profile", + "asset": "asset", + "entity-view": "entity view", + "edge": "edge", + "rule-chain": "rule chain", + "rule-node": "rule node", + "dashboard": "dashboard", + "alarm": "alarm", + "entity-group": "entity group", + "api-usage-state": "api usage state", + "widget-type": "widget", + "widgets-bundle": "widgets bundle", + "converter": "data converter", + "integration": "integration", + "scheduler-event": "scheduler event", + "blob-entity": "blob entity", + "report-template": "report template", + "report": "report", + "role": "role", + "group-permission": "group permission", + "tb-resource": "resource", + "ota-package": "ota package", + "job": "task", + "rpc": "rpc", + "queue": "queue", + "queue-stats": "queue statistics", + "notification": "notification", + "notification-request": "notification request", + "domain": "domain", + "oauth2-client": "oauth 2.0 client", + "mobile-app": "mobile application", + "mobile-app-bundle": "mobile bundle", + "admin-settings": "admin settings", + "ai-model": "ai model", + "secret": "secret storage", + "api-key": "api key", + "agent": "agent", + "agent-profile": "agent profile", + "agent-application": "application", + "agent-app-profile": "application profile", + "agent-app-event": "agent app event", + "agent-app-unit": "agent app unit", + "agent-bulk-action": "bulk action" + }, + "states": "States", + "aliases": "Entity aliases", + "filters": "Filters", + "nothing-found": "Nothing matched.", + "no-data": "No data.", + "no-attributes": "No attributes.", + "no-attribute-keys": "No attribute keys.", + "now": "now", + "cut-short": "Cut short: only the start of it was reported.", + "more": "and {{count}} more", + "series": "{{points}} points · {{min}} – {{max}} · last {{last}}", + "installs": "{{count}} installs", + "hub-device": "Device", + "on-iot-hub": "On IoT Hub", + "show": "Show", + "yes": "Yes", + "no": "No", + "fact": { + "integration-type": "Integration type", + "link": "Link", + "subject": "Subject", + "last-connect": "Last connected", + "version": "Version", + "branch": "Branch", + "added": "Added", + "modified": "Modified", + "removed": "Removed", + "comment": "Comment", + "reference": "Reference", + "tested": "Tested before saving", + "permissions": "Permissions", + "status": "Status", + "sends-at": "Sends at", + "recipients": "Recipients", + "delivered": "Delivered", + "error": "Error", + "dashboard": "Dashboard", + "entities-checked": "Entities checked", + "email": "Email", + "owner": "Owner", + "members": "Members", + "user-groups": "User groups", + "activation": "Activation", + "activation-link": "Activation link", + "resolves": "Resolves", + "entities": "Entities", + "entity": "Entity", + "multiple": "Several entities", + "title": "Title", + "widget-type": "Widget", + "state": "State", + "alias": "Entity alias", + "keys": "Keys", + "size": "Size", + "theme": "Theme", + "time-window": "Time window", + "format": "Format", + "page": "Page", + "file-name": "File name", + "header-footer": "Header and footer", + "component": "Component", + "path": "Path", + "height": "Height", + "state-id": "State ID", + "type": "Type", + "on": "On", + "arguments": "Arguments", + "expression": "Expression", + "output": "Output", + "severities": "Severities", + "clears": "Clears itself", + "settings": "Settings", + "created": "Created", + "disabled": "Disabled", + "description": "Description", + "design": "Design", + "embeds": "Embedded states", + "aliases": "Entity aliases", + "label": "Label", + "profile": "Profile", + "customer": "Customer", + "gateway": "Gateway" + } + }, + "action": { + "search-devices": { + "run": "Looking up devices", + "done": "Looked up devices" + }, + "search-assets": { + "run": "Looking up assets", + "done": "Looked up assets" + }, + "search-dashboards": { + "run": "Looking up dashboards", + "done": "Looked up dashboards" + }, + "search-customers": { + "run": "Looking up customers", + "done": "Looked up customers" + }, + "search-users": { + "run": "Looking up users", + "done": "Looked up users" + }, + "search-tenant": { + "run": "Searching the tenant", + "done": "Searched the tenant" + }, + "read-entity": { + "run": "Reading the record", + "done": "Read the record" + }, + "read-latest-values": { + "run": "Reading the latest values", + "done": "Read the latest values" + }, + "read-history": { + "run": "Reading the history", + "done": "Read the history" + }, + "read-telemetry-keys": { + "run": "Reading the telemetry keys", + "done": "Read the telemetry keys" + }, + "read-attributes": { + "run": "Reading attributes", + "done": "Read attributes" + }, + "save-attributes": { + "run": "Updating the attributes", + "done": "Updated the attributes" + }, + "delete-attributes": { + "run": "Deleting the attributes", + "done": "Deleted the attributes" + }, + "read-relations": { + "run": "Following relations", + "done": "Followed relations" + }, + "read-credentials": { + "run": "Reading the device credentials", + "done": "Read the device credentials" + }, + "recalculate-history": { + "run": "Recalculating history", + "done": "Recalculated history" + }, + "create-dashboard": { + "run": "Creating the dashboard", + "done": "Created the dashboard" + }, + "update-dashboard": { + "run": "Updating the dashboard", + "done": "Updated the dashboard" + }, + "add-dashboard-state": { + "run": "Adding a dashboard state", + "done": "Added a dashboard state" + }, + "update-dashboard-state": { + "run": "Updating the dashboard state", + "done": "Updated the dashboard state" + }, + "add-entity-alias": { + "run": "Adding an entity alias", + "done": "Added an entity alias" + }, + "update-entity-alias": { + "run": "Updating the entity alias", + "done": "Updated the entity alias" + }, + "read-entity-alias": { + "run": "Reading the entity alias", + "done": "Read the entity alias" + }, + "add-dashboard-filter": { + "run": "Adding a dashboard filter", + "done": "Added a dashboard filter" + }, + "update-dashboard-filter": { + "run": "Updating the dashboard filter", + "done": "Updated the dashboard filter" + }, + "read-dashboard-filter": { + "run": "Reading the dashboard filter", + "done": "Read the dashboard filter" + }, + "read-dashboard": { + "run": "Reading the dashboard", + "done": "Read the dashboard" + }, + "create-device": { + "run": "Creating the device", + "done": "Created the device" + }, + "update-device": { + "run": "Updating the device", + "done": "Updated the device" + }, + "create-calculated-field": { + "run": "Creating the calculated field", + "done": "Created the calculated field" + }, + "update-calculated-field": { + "run": "Updating the calculated field", + "done": "Updated the calculated field" + }, + "create-alarm-rule": { + "run": "Creating the alarm rule", + "done": "Created the alarm rule" + }, + "update-alarm-rule": { + "run": "Updating the alarm rule", + "done": "Updated the alarm rule" + }, + "create-notification-target": { + "run": "Creating the notification recipients", + "done": "Created the notification recipients" + }, + "update-notification-target": { + "run": "Updating the notification recipients", + "done": "Updated the notification recipients" + }, + "create-notification-template": { + "run": "Creating the notification template", + "done": "Created the notification template" + }, + "update-notification-template": { + "run": "Updating the notification template", + "done": "Updated the notification template" + }, + "create-notification-rule": { + "run": "Creating the notification rule", + "done": "Created the notification rule" + }, + "update-notification-rule": { + "run": "Updating the notification rule", + "done": "Updated the notification rule" + }, + "add-widget": { + "run": "Adding a widget", + "done": "Added a widget" + }, + "add-widgets": { + "run": "Adding widgets", + "done": "Added widgets" + }, + "add-scada-connectors": { + "run": "Drawing pipes", + "done": "Drew pipes" + }, + "update-widget": { + "run": "Updating the widget", + "done": "Updated the widget" + }, + "place-widgets": { + "run": "Placing the widgets", + "done": "Placed the widgets" + }, + "read-widget": { + "run": "Reading the widget", + "done": "Read the widget" + }, + "lay-out-dashboard": { + "run": "Laying out the dashboard", + "done": "Laid out the dashboard" + }, + "read-dashboard-page": { + "run": "Reading the dashboard page", + "done": "Read the dashboard page" + }, + "search-iot-hub": { + "run": "Searching IoT Hub", + "done": "Searched IoT Hub" + }, + "read-iot-hub-item": { + "run": "Reading the IoT Hub item", + "done": "Read the IoT Hub item" + }, + "list-installed-iot-hub-items": { + "run": "Checking what is installed from IoT Hub", + "done": "Checked what is installed from IoT Hub" + }, + "install-iot-hub-item": { + "run": "Installing from IoT Hub", + "done": "Installed from IoT Hub" + }, + "read-connection-settings": { + "run": "Looking up the connection settings", + "done": "Looked up the connection settings" + }, + "read-api-usage": { + "run": "Checking the API usage", + "done": "Checked the API usage" + }, + "read-audit-logs": { + "run": "Reading the audit log", + "done": "Read the audit log" + }, + "read-tasks": { + "run": "Checking the task manager", + "done": "Checked the task manager" + }, + "save-image": { + "run": "Adding the image", + "done": "Added the image" + }, + "update-alarms": { + "acknowledge": {"run": "Acknowledging the alarms", "done": "Acknowledged the alarms"}, + "clear": {"run": "Clearing the alarms", "done": "Cleared the alarms"}, + "assign": {"run": "Assigning the alarms", "done": "Assigned the alarms"}, + "unassign": {"run": "Unassigning the alarms", "done": "Unassigned the alarms"}, + "comment": {"run": "Commenting on the alarms", "done": "Commented on the alarms"}, + "other": {"run": "Updating the alarms", "done": "Updated the alarms"} + }, + "delete-alarm": { + "run": "Deleting the alarm", + "done": "Deleted the alarm" + }, + "create-asset": { + "run": "Creating the asset", + "done": "Created the asset" + }, + "update-asset": { + "run": "Updating the asset", + "done": "Updated the asset" + }, + "delete-asset": { + "run": "Deleting the asset", + "done": "Deleted the asset" + }, + "save-relations": { + "run": "Changing the relations", + "done": "Changed the relations" + }, + "read-versions": { + "run": "Reading the versions", + "done": "Read the versions" + }, + "read-gateway-status": { + "run": "Checking the gateway", + "done": "Checked the gateway" + }, + "read-ota": { + "run": "Checking the OTA updates", + "done": "Checked the OTA updates" + }, + "read-edges": { + "run": "Checking the edges", + "done": "Checked the edges" + }, + "read-edge-events": { + "run": "Reading the edge's downlinks", + "done": "Read the edge's downlinks" + }, + "read-edge-instructions": { + "run": "Getting the edge instructions", + "done": "Got the edge instructions" + }, + "save-edge": { + "run": "Saving the edge", + "done": "Saved the edge" + }, + "assign-to-edge": { + "run": "Changing what the edge receives", + "done": "Changed what the edge receives" + }, + "sync-edge": { + "run": "Syncing the edge", + "done": "Started the edge sync" + }, + "delete-edge": { + "run": "Deleting the edge", + "done": "Deleted the edge" + }, + "read-rule-chain-templates": { + "run": "Reading the edge rule chains", + "done": "Read the edge rule chains" + }, + "set-rule-chain-template": { + "run": "Updating the edge rule chain", + "done": "Updated the edge rule chain" + }, + "read-agents": { + "run": "Checking the agents", + "done": "Checked the agents" + }, + "read-agent-instructions": { + "run": "Getting the agent command", + "done": "Got the agent command" + }, + "save-agent": { + "run": "Saving the agent", + "done": "Saved the agent" + }, + "install-agent-application": { + "run": "Installing the application", + "done": "Started the install" + }, + "run-agent-operation": { + "run": "Starting the operation", + "done": "Started the operation" + }, + "read-agent-profiles": { + "run": "Reading the agent profiles", + "done": "Read the agent profiles" + }, + "save-agent-profile": { + "run": "Saving the agent profile", + "done": "Saved the agent profile" + }, + "save-agent-app-profile": { + "run": "Saving the application profile", + "done": "Saved the application profile" + }, + "run-agent-bulk-action": { + "run": "Starting the bulk action", + "done": "Started the bulk action" + }, + "wait-agent-operation": { + "run": "Waiting for the agent", + "done": "The agent finished" + }, + "delete-agent": { + "run": "Deleting the agent", + "done": "Deleted the agent" + }, + "delete-agent-profile": { + "run": "Deleting the agent profile", + "done": "Deleted the agent profile" + }, + "delete-agent-app-profile": { + "run": "Deleting the application profile", + "done": "Deleted the application profile" + }, + "read-white-labeling": { + "run": "Reading the white labeling", + "done": "Read the white labeling" + }, + "read-website-brand": { + "run": "Reading the website's brand", + "done": "Read the website's brand" + }, + "save-white-labeling": { + "run": "Saving the white labeling", + "done": "Saved the white labeling" + }, + "read-mail-templates": { + "run": "Reading the mail templates", + "done": "Read the mail templates" + }, + "save-mail-template": { + "run": "Changing the emails", + "done": "Changed the emails" + }, + "read-custom-translation": { + "run": "Reading the custom translation", + "done": "Read the custom translation" + }, + "save-custom-translation": { + "run": "Changing the texts", + "done": "Changed the texts" + }, + "read-custom-menus": { + "run": "Reading the custom menus", + "done": "Read the custom menus" + }, + "read-security-settings": { + "run": "Reading the security settings", + "done": "Read the security settings" + }, + "read-mobile-center": { + "run": "Reading the mobile center", + "done": "Read the mobile center" + }, + "save-mobile-app": { + "run": "Saving the mobile app", + "done": "Saved the mobile app" + }, + "save-mobile-bundle": { + "run": "Saving the mobile bundle", + "done": "Saved the mobile bundle" + }, + "save-mobile-qr-code": { + "run": "Saving the QR code", + "done": "Saved the QR code" + }, + "read-scheduler-events": { + "run": "Reading the scheduler", + "done": "Read the scheduler" + }, + "save-scheduler-event": { + "run": "Saving the scheduler event", + "done": "Saved the scheduler event" + }, + "save-two-factor-settings": { + "run": "Saving the two-factor settings", + "done": "Saved the two-factor settings" + }, + "save-oauth2-domain": { + "run": "Saving the domain's sign-in", + "done": "Saved the domain's sign-in" + }, + "read-my-account": { + "run": "Reading your account", + "done": "Read your account" + }, + "read-mail-server": { + "run": "Reading the mail server", + "done": "Read the mail server" + }, + "save-mail-server": { + "run": "Saving the mail server", + "done": "Saved the mail server" + }, + "save-my-profile": { + "run": "Saving your profile", + "done": "Saved your profile" + }, + "save-my-two-factor": { + "run": "Saving your two-factor methods", + "done": "Saved your two-factor methods" + }, + "update-api-key": { + "run": "Saving the API key", + "done": "Saved the API key" + }, + "save-custom-menu": { + "run": "Saving the custom menu", + "done": "Saved the custom menu" + }, + "save-ota-package": { + "run": "Creating the OTA package", + "done": "Created the OTA package" + }, + "assign-ota-package": { + "run": "Assigning the OTA package", + "done": "Assigned the OTA package" + }, + "delete-ota-package": { + "run": "Deleting the OTA package", + "done": "Deleted the OTA package" + }, + "delete-mobile-app": { + "run": "Deleting the mobile app", + "done": "Deleted the mobile app" + }, + "delete-mobile-bundle": { + "run": "Deleting the mobile bundle", + "done": "Deleted the mobile bundle" + }, + "delete-scheduler-event": { + "run": "Deleting the scheduler event", + "done": "Deleted the scheduler event" + }, + "create-report-template": { + "run": "Creating the report template", + "done": "Created the report template" + }, + "update-report-template": { + "run": "Saving the report template", + "done": "Saved the report template" + }, + "read-report-template": { + "run": "Reading the report template", + "done": "Read the report template" + }, + "read-report-component": { + "run": "Reading the component", + "done": "Read the component" + }, + "add-report-components": { + "run": "Adding report components", + "done": "Added report components" + }, + "update-report-component": { + "run": "Changing a report component", + "done": "Changed a report component" + }, + "move-report-component": { + "run": "Moving a report component", + "done": "Moved a report component" + }, + "save-report-alias": { + "run": "Saving the entity alias", + "done": "Saved the entity alias" + }, + "save-report-filter": { + "run": "Saving the filter", + "done": "Saved the filter" + }, + "test-report-template": { + "run": "Generating a test report", + "done": "Checked the report" + }, + "read-reports": { + "run": "Reading the reports", + "done": "Read the reports" + }, + "save-scheduled-report": { + "run": "Saving the scheduled report", + "done": "Saved the scheduled report" + }, + "generate-report": { + "run": "Generating the report", + "done": "Generated the report" + }, + "delete-report": { + "run": "Deleting the report", + "done": "Deleted the report" + }, + "read-widgets": { + "run": "Reading the widgets library", + "done": "Read the widgets library" + }, + "read-scada-symbols": { + "run": "Reading the SCADA symbols", + "done": "Read the SCADA symbols" + }, + "read-scada-symbol": { + "run": "Reading the SCADA symbol", + "done": "Read the SCADA symbol" + }, + "read-scada-symbol-parts": { + "run": "Reading the symbol's {{parts}}", + "done": "Read the symbol's {{parts}}" + }, + "build-widget": { + "run": "Writing the widget", + "done": "Wrote the widget" + }, + "build-scada-symbol": { + "run": "Drawing the SCADA symbol", + "done": "Drew the SCADA symbol" + }, + "copy-scada-symbol": { + "run": "Copying the SCADA symbol", + "done": "Copied the SCADA symbol" + }, + "update-scada-symbol": { + "run": "Changing the SCADA symbol", + "done": "Changed the SCADA symbol" + }, + "check-scada-symbol": { + "run": "Running the SCADA symbol", + "done": "Ran the SCADA symbol" + }, + "create-scada-symbol-widget": { + "run": "Adding the symbol to the widgets library", + "done": "Added the symbol to the widgets library" + }, + "read-widget-parts": { + "run": "Reading the widget's {{parts}}", + "done": "Read the widget's {{parts}}" + }, + "read-widget-type": { + "run": "Reading the widget", + "done": "Read the widget" + }, + "create-widget": { + "run": "Creating the widget", + "done": "Created the widget" + }, + "update-widget-type": { + "run": "Changing the widget", + "done": "Changed the widget" + }, + "check-widget": { + "run": "Running the widget in the preview", + "done": "Ran the widget in the preview" + }, + "save-widgets-bundle": { + "run": "Saving the widgets bundle", + "done": "Saved the widgets bundle" + }, + "delete-widget-type": { + "run": "Deleting the widget", + "done": "Deleted the widget" + }, + "delete-widgets-bundle": { + "run": "Deleting the widgets bundle", + "done": "Deleted the widgets bundle" + }, + "delete-report-template": { + "run": "Deleting the report template", + "done": "Deleted the report template" + }, + "delete-report-component": { + "run": "Deleting the report component", + "done": "Deleted the report component" + }, + "delete-report-alias": { + "run": "Deleting the entity alias", + "done": "Deleted the entity alias" + }, + "delete-report-filter": { + "run": "Deleting the filter", + "done": "Deleted the filter" + }, + "delete-custom-menu": { + "run": "Deleting the custom menu", + "done": "Deleted the custom menu" + }, + "commit-version": { + "run": "Saving a version", + "done": "Saved a version" + }, + "restore-version": { + "run": "Restoring from the version", + "done": "Restored from the version" + }, + "create-entity-view": { + "run": "Creating the entity view", + "done": "Created the entity view" + }, + "update-entity-view": { + "run": "Updating the entity view", + "done": "Updated the entity view" + }, + "create-asset-profile": { + "run": "Creating the asset profile", + "done": "Created the asset profile" + }, + "update-asset-profile": { + "run": "Updating the asset profile", + "done": "Updated the asset profile" + }, + "create-secret": { + "run": "Creating the secret", + "done": "Created the secret" + }, + "update-secret": { + "run": "Updating the secret", + "done": "Updated the secret" + }, + "create-ai-model": { + "run": "Testing and adding the AI model", + "done": "Added the AI model" + }, + "update-ai-model": { + "run": "Updating the AI model", + "done": "Updated the AI model" + }, + "create-resource": { + "run": "Adding the resource", + "done": "Added the resource" + }, + "update-resource": { + "run": "Updating the resource", + "done": "Updated the resource" + }, + "read-platform-settings": { + "run": "Reading the platform settings", + "done": "Read the platform settings" + }, + "save-platform-settings": { + "run": "Saving the platform settings", + "done": "Saved the platform settings" + }, + "delete-image": { + "run": "Deleting the image", + "done": "Deleted the image" + }, + "delete-entity-view": { + "run": "Deleting the entity view", + "done": "Deleted the entity view" + }, + "delete-asset-profile": { + "run": "Deleting the asset profile", + "done": "Deleted the asset profile" + }, + "save-credentials": { + "run": "Changing the device credentials", + "done": "Changed the device credentials" + }, + "test-converter": { + "run": "Testing the converter", + "done": "Tested the converter" + }, + "read-converter-library": { + "run": "Reading the converter library", + "done": "Read the converter library" + }, + "create-device-profile": { + "run": "Creating the device profile", + "done": "Created the device profile" + }, + "update-device-profile": { + "run": "Updating the device profile", + "done": "Updated the device profile" + }, + "create-converter": { + "run": "Creating the converter", + "done": "Created the converter" + }, + "update-converter": { + "run": "Updating the converter", + "done": "Updated the converter" + }, + "create-integration": { + "run": "Creating the integration", + "done": "Created the integration" + }, + "update-integration": { + "run": "Updating the integration", + "done": "Updated the integration" + }, + "delete-device-profile": { + "run": "Deleting the device profile", + "done": "Deleted the device profile" + }, + "delete-integration": { + "run": "Deleting the integration", + "done": "Deleted the integration" + }, + "delete-converter": { + "run": "Deleting the converter", + "done": "Deleted the converter" + }, + "check-connection": { + "run": "Checking the connection", + "done": "Checked the connection" + }, + "wait-for-data": { + "run": "Waiting for data", + "done": "Waited for data" + }, + "delete-secret": { + "run": "Deleting the secret", + "done": "Deleted the secret" + }, + "delete-ai-model": { + "run": "Deleting the AI model", + "done": "Deleted the AI model" + }, + "delete-resource": { + "run": "Deleting the resource", + "done": "Deleted the resource" + }, + "research-device": { + "run": "Researching the device", + "done": "Researched the device" + }, + "search-web": { + "run": "Searching the web", + "done": "Searched the web" + }, + "read-page": { + "run": "Reading the page", + "done": "Read the page" + }, + "read-site": { + "run": "Reading {{site}}", + "done": "Read {{site}}" + }, + "delete-calculated-field": { + "run": "Deleting the calculated field", + "done": "Deleted the calculated field" + }, + "delete-alarm-rule": { + "run": "Deleting the alarm rule", + "done": "Deleted the alarm rule" + }, + "delete-notification-rule": { + "run": "Deleting the notification rule", + "done": "Deleted the notification rule" + }, + "delete-notification-target": { + "run": "Deleting the notification recipients", + "done": "Deleted the notification recipients" + }, + "delete-notification-template": { + "run": "Deleting the notification template", + "done": "Deleted the notification template" + }, + "delete-dashboard": { + "run": "Deleting the dashboard", + "done": "Deleted the dashboard" + }, + "delete-widget": { + "run": "Deleting the widget", + "done": "Deleted the widget" + }, + "delete-dashboard-state": { + "run": "Deleting the dashboard state", + "done": "Deleted the dashboard state" + }, + "delete-entity-alias": { + "run": "Deleting the entity alias", + "done": "Deleted the entity alias" + }, + "delete-dashboard-filter": { + "run": "Deleting the dashboard filter", + "done": "Deleted the dashboard filter" + }, + "delete-device": { + "run": "Deleting the device", + "done": "Deleted the device" + }, + "create-customer": { + "run": "Creating the customer", + "done": "Created the customer" + }, + "update-customer": { + "run": "Updating the customer", + "done": "Updated the customer" + }, + "create-user": { + "run": "Creating the user", + "done": "Created the user" + }, + "update-user": { + "run": "Updating the user", + "done": "Updated the user" + }, + "create-entity-group": { + "run": "Creating the group", + "done": "Created the group" + }, + "update-entity-group": { + "run": "Renaming the group", + "done": "Renamed the group" + }, + "create-role": { + "run": "Creating the role", + "done": "Created the role" + }, + "update-role": { + "run": "Updating the role", + "done": "Updated the role" + }, + "update-group-members": { + "run": "Changing the group's members", + "done": "Changed the group's members" + }, + "change-owner": { + "run": "Changing the owner", + "done": "Changed the owner" + }, + "share-group": { + "run": "Sharing the group", + "done": "Shared the group" + }, + "grant-role": { + "run": "Giving the role", + "done": "Gave the role" + }, + "read-access": { + "run": "Reading who can do what", + "done": "Read who can do what" + }, + "check-dashboard-access": { + "run": "Checking what the customer can see", + "done": "Checked what the customer can see" + }, + "delete-customer": { + "run": "Deleting the customer", + "done": "Deleted the customer" + }, + "delete-user": { + "run": "Deleting the user", + "done": "Deleted the user" + }, + "delete-entity-group": { + "run": "Deleting the group", + "done": "Deleted the group" + }, + "delete-role": { + "run": "Deleting the role", + "done": "Deleted the role" + }, + "delete-grant": { + "run": "Taking back the role", + "done": "Took back the role" + }, + "send-notification": { + "run": "Sending the notification", + "done": "Sent the notification" + }, + "read-notifications": { + "run": "Reading notifications", + "done": "Read notifications" + }, + "mark-notifications-read": { + "run": "Marking notifications as read", + "done": "Marked notifications as read" + }, + "save-notification-settings": { + "run": "Changing notification delivery", + "done": "Changed notification delivery" + }, + "save-notification-preferences": { + "run": "Changing notification preferences", + "done": "Changed notification preferences" + }, + "delete-sent-notification": { + "run": "Deleting the sent notification", + "done": "Deleted the sent notification" + }, + "delete-inbox-notification": { + "run": "Deleting the notification", + "done": "Deleted the notification" + }, + "delete-other": { + "run": "Deleting", + "done": "Deleted" + }, + "other": { + "run": "Working on a step", + "done": "Finished a step" + }, + "create-solution": { + "run": "Creating the solution", + "done": "The solution is created" + }, + "install-solution": { + "run": "Installing the solution", + "done": "The solution is installed" + }, + "failed": "Failed while {{words}}", + "auto-approved": "{{words}} · auto-approved", + "details": "Details", + "request": "Request", + "result": "Result", + "payload": "Payload", + "script": "Script", + "metadata": "Metadata", + "output": "Output", + "error": "Error", + "template": "Template", + "event": "Event", + "account": "Account", + "mail-server": "Mail server", + "qr-code": "QR code", + "settings": "Settings", + "try-again": "Try again", + "try-again-prompt": "Try that again" + }, + "go-to-end": "Go to the end", + "resume": "Resume", + "run-failed": "The run stopped with an error.", + "new-count": "{{ count }} new", + "start-a-task": "Start a task", + "credits": { + "title": "AI credits", + "used": "{{used}} of {{max}} used this month", + "resets": "Resets on {{date}}.", + "left": "{left} { count, plural, =1 {credit} other {credits} } left", + "none-left": "No credits left", + "aria": "AI credits: {{used}} of {{max}} used this month" + }, + "hand-over": { + "stop-listening": "Stop listening", + "test-first": "Test from this computer first", + "what-you-see": "What you should see", + "send-test": "Send a test value", + "send-test-here": "Send a test value from here", + "send-test-tip": "Sends one value as the device, marked as a test; the wait keeps listening for the device itself", + "test-sent": "A test value went in at {{time}} and is on the device's latest telemetry. The wait keeps listening for the device itself.", + "test-failed": "The test value did not go through: {{error}}.", + "needs-you": "Needs you", + "fold": "Fold", + "unfold": "Show the steps", + "gateway-connected": "{{name}} connected at {{time}}.", + "arrived-message": "The first message arrived at {{time}}.", + "arrived-message-from": "The first message from {{name}} arrived at {{time}}.", + "arrived-uplink": "The first uplink arrived at {{time}}.", + "arrived-uplink-from": "The first uplink from {{name}} arrived at {{time}}.", + "arrived-gateway": "The gateway connected at {{time}}.", + "arrived-gateway-from": "{{name}} connected at {{time}}.", + "arrived-keys": "The first message arrived at {{time}}, with {{count}} keys:", + "arrived-keys-from": "The first message from {{name}} arrived at {{time}}, with {{count}} keys:", + "arrived-key": "The first message arrived at {{time}}, with 1 key:", + "arrived-key-from": "The first message from {{name}} arrived at {{time}}, with 1 key:", + "show": "Show", + "hide": "Hide", + "copied": "Copied", + "wait-message": "listening for the first message", + "wait-uplink": "listening for the first uplink", + "wait-gateway": "listening for the gateway", + "nothing-heard": "nothing heard for {{minutes}} min", + "not-decoded": "uplinks arrived but were not decoded", + "keep-waiting": "It is on now, keep waiting", + "keep-waiting-prompt": "It is on. Keep waiting for the data.", + "what-wrong": "What could be wrong?", + "what-wrong-prompt": "Nothing arrived. What could be wrong?" + }, + "credits-out": { + "title": "AI credits used up", + "tenant-text": "Your tenant has used all {{limit}} AI credits for this month. They reset on {{date}}, or your system administrator can raise the limit.", + "tenant-text-plain": "Your tenant has used all its AI credits for this month. They reset on {{date}}, or your system administrator can raise the limit.", + "pool-text": "All available AI credits have been used for this month. You can ask your administrator to add more AI credits.", + "request": "Request more credits", + "sent": "Request sent to your system administrator.", + "failed": "Couldn't send the request. Try again.", + "view-usage": "View usage" + }, + "limit-out": { + "entity-title": "{{entities}} limit reached", + "tenant-text": "Your tenant can have up to {{limit}} {{entities}}. Your system administrator can raise the limit.", + "tenant-text-plain": "Your tenant has reached its limit of {{entities}}. Your system administrator can raise the limit.", + "license-text": "Your license allows no more {{entities}}. Your system administrator can raise the limit in License management.", + "license-text-old": "You have reached the maximum {{entities}} allowed by your subscription plan. You can upgrade the plan to raise your limits.", + "feature-title": "{{feature}} not included in your plan", + "feature": { + "white-labeling": "White labeling", + "integrations": "Integrations", + "scheduler": "Scheduler", + "reporting": "Reports" + }, + "white-labeling-text": "With White labeling, your brand replaces ThingsBoard's on the login page, in the mail you send and on every page your customers work in.", + "pack-text": "It comes with the Professional Pack. Request access and your system administrator gets your request.", + "license-required": "License required", + "request": "Request a higher limit", + "manage-license": "Manage license", + "sent": "Request sent to your system administrator.", + "failed": "Couldn't send the request. Try again.", + "view-usage": "View usage" + }, + "get-started": { + "title": "Get started", + "heading": "What are you building, or what device do you have?", + "take-tour": "Take the tour", + "suggestion": "A freezer in Store 12 on Main Street: an ESP32 reads the temperature and the door and publishes over MQTT. Alert me if it gets warm.", + "examples": "Start from an example", + "examples-hint": "A card puts its prompt in the composer, to read and change before you send it.", + "example": { + "mqtt": { + "title": "A freezer sensor sending over MQTT", + "what": "A device, its dashboard, an alert; you put the token on it", + "prompt": "A freezer in Store 12 on Main Street: an ESP32 reads the temperature and the door and publishes over MQTT. Alert me if it gets warm." + }, + "things-stack": { + "title": "EM300-TH sensors on The Things Stack", + "what": "An integration with the library decoder; you create an API key", + "prompt": "Milesight EM300-TH sensors in the cold rooms of my store, registered on The Things Stack. Alert me if a room gets warm." + }, + "modbus": { + "title": "Freezer controllers on Modbus", + "what": "A gateway and a Modbus connector; you run it on the store PC", + "prompt": "Our six freezer controllers speak Modbus through a serial-to-IP box at 192.168.1.50. Alert me if a freezer gets warm." + }, + "datasheet": { + "title": "A sensor, from its datasheet", + "what": "The keys and units read from the PDF; you put the token on it", + "prompt": "Connect the sensor in this datasheet: an SHT31 on an ESP32 in the Store 12 cold room, publishing over MQTT. Alert me if it gets warm." + } + } + }, + "create-solution": "Create a solution", + "create-solution-hint": "Devices, dashboards and alarms, set up as one", + "create-solution-start": "Start", + "cli": { + "title": "ThingsBoard CLI", + "kicker": "ThingsBoard CLI", + "connect-agents": "Connect to your agents", + "strip-tip": "ThingsBoard CLI: connect to your agents", + "close": "Close, back to Get started", + "band": { + "heading": "Build it with your coding agent", + "line": "Claude Code or Antigravity, through the ThingsBoard CLI", + "action": "Try CLI now" + }, + "hero": { + "title": "Build on ThingsBoard with your coding agent", + "lead": "Describe your devices in plain words. Claude Code or Antigravity builds the solution in minutes.", + "start": "Get started", + "docs": "CLI docs" + }, + "term": { + "label": "Example sessions", + "picture": "A coding agent in a terminal: {{about}}.", + "thinking": "Thinking…", + "running": "Running…", + "done": "Done in {{seconds}}s", + "connected": "Connected to eu.thingsboard.cloud", + "detected": "Coding agent detected", + "office-sensor": { + "about": "asked for an office sensor with a CO2 alert, the agent writes the device, an alarm rule and a dashboard, asks before the deploy, then deploys and streams demo data", + "you": "Add my office sensor: temperature, humidity and CO2. Alert me when CO2 goes above 1000.", + "written": "office: device, profile, alarm rule and dashboard written", + "ready": "Done. The office sensor is ready:", + "device": "Device Office Sensor, its profile with temperature, humidity and co2", + "alarm": "Alarm rule CO2 High, above 1000 ppm", + "dashboard": "Dashboard Office: three charts and the alarm list", + "ask": "Deploy to ThingsBoard and stream live demo data for 5 minutes?", + "stream": "Deploy and stream live data", + "deploy-only": "Deploy only", + "not-now": "Not now", + "deployed": "office deployed · 4 entities", + "streaming": "streaming to Office Sensor" + }, + "smart-retail": { + "about": "asked for a smart retail solution, the agent designs it, asks how to approve the build, shows the dashboards and builds after a yes", + "devices": "eu.thingsboard.cloud · 0 devices", + "connected": "Connected to ThingsBoard, nothing built yet.", + "you": "Create a smart retail solution: three stores with freezers, fridges and door sensors.", + "designed": "3 stores · 36 devices · 4 dashboards · 2 roles", + "approve": "The design is ready. How do you want to approve the build?", + "step": "Step by step", + "whole": "The whole build at once", + "first": "First, the dashboards:", + "overview": "Chain overview: the stores on a map, open alarms by store", + "store": "Store: freezers, fridges and doors, with their alarms", + "build": "Build the devices and dashboards?", + "yes": "Yes", + "not-yet": "Not yet", + "built": "smart-retail: 52 entities written · validated", + "next": "Built and validated. The freezer alarms come next." + }, + "freezer-limits": { + "about": "asked for an alarm limit on each freezer, the agent updates the solution, lists what changed, asks before the push and deploys after a yes", + "you": "Each freezer needs its own alarm limit. Let me set the limit from the dashboard.", + "updated": "attribute, alarm rule and dashboard updated", + "done": "Done. Each freezer now has its own temperature threshold:", + "attribute": "New attribute temperatureThreshold, set to -15 °C on all freezers", + "alarm": "Freezer Too Warm alarm now reads each freezer’s own threshold", + "dashboard": "Dashboard: the freezer view has a Temperature Threshold card", + "ask": "Want me to push this to dev?", + "push": "Push to dev", + "not-now": "Not now", + "deployed": "smart-retail deployed → dev · 9 entities" + } + }, + "how-to-set-up": "How to set up", + "way": { + "terminal": "Install it yourself", + "agent": "Ask your agent" + }, + "terminal": "Terminal", + "mac-linux": "macOS or Linux", + "windows": "Windows", + "setup-prompt-label": "Setup prompt", + "setup-prompt": "Set up ThingsBoard CLI in this folder:\n\n1. Install or upgrade it. On macOS or Linux, run: curl -LsSf https://thingsboard.io/cli/install.sh | sh\n On Windows, run: powershell -ExecutionPolicy ByPass -c \"irm https://thingsboard.io/cli/install.ps1 | iex\"\n2. Run \"tb init --agent-format --browser\". Use \"claude\" for Claude Code or \"antigravity\" for Antigravity. It opens a page where I enter my ThingsBoard URL and API key. Tell me to complete the page, then wait. Never ask me for the API key in the chat, and never print secrets.\n3. Check the connection with \"tb device list\".\n\nIf everything works, reply with one sentence: the setup is complete, and I must restart you to load the ThingsBoard skills. Then show the restart commands for you only. Claude Code: type /exit, then run claude --continue. Antigravity: close it, then run agy in this folder. If a step fails, tell me what failed and how to fix it.", + "how": { + "title": "How it works", + "agent": { + "title": "Agents do the work", + "text": "Claude Code or Antigravity, with the CLI’s ThingsBoard skills." + }, + "files": { + "title": "Solutions live in git", + "text": "Devices, dashboards and alarms as JSON, every step a commit.", + "commit": "Alarm limits" + }, + "deploy": { + "title": "Nothing goes live unasked", + "text": "The CLI checks the files against ThingsBoard before any deploy.", + "question": "Push this to dev?", + "yes": "1. Push to dev", + "no": "2. Not now" + } + }, + "steps": { + "title": "Get started", + "hint": "About 10 minutes to live data on a dashboard." + }, + "setup": { + "title": "Set up the CLI", + "run-install": "Run the install command", + "accept-folder": "Accept the project folder", + "accept": "Press Enter at “Project folder” to keep {{folder}} Press Enter again when the setup offers to connect.", + "paste-url": "Paste your ThingsBoard URL", + "url": "URL", + "copy-url": "Copy the url", + "api-key": "Create and paste an API key", + "api-key-text": "The setup opens Security in your browser. Under API keys, click Manage, then + Generate, and paste the key in the terminal.", + "open-api-keys": "Open API keys", + "start-agent": "Start your agent", + "start-agent-text": "Press Enter at “Start Claude Code now?” or “Start Antigravity now?” Your agent opens in the project folder with the ThingsBoard skills loaded.", + "both-agents": "With both agents installed, the setup first asks which one to set up. Pick {{claude}} or {{antigravity}}", + "come-back-folder": "To come back later, start your agent from the project folder:", + "agent-start": "Start your agent in a new folder", + "agent-send": "Send the setup prompt", + "agent-allow": "Allow the commands your agent asks to run.", + "agent-connect": "Choose your ThingsBoard on the Connect page", + "agent-connect-text": "The page opens in your browser. Pick your cloud region, or pick “Your own server” and paste the URL.", + "agent-key": "Create an API key for the Connect page", + "agent-key-text": "Click “Create an API key”. Under API keys, click Manage, then + Generate, and paste the key on the page. The key stays out of the chat.", + "agent-restart": "Restart your agent", + "restart": "Skills load only when an agent starts. Type {{exit}} in Claude Code, or close Antigravity, then run:", + "come-back": "To come back later, start your agent from the same folder." + }, + "describe": { + "title": "Describe what to build", + "text": "Tell your agent what sends data, what the data looks like, what to show and when to alert.", + "examples": "Examples", + "prompt": "Prompt", + "sensor": { + "label": "Start with one sensor", + "what": "Your agent writes one device, one dashboard and one alarm, then asks to deploy." + }, + "solution": { + "label": "Build a full solution", + "what": "Your agent asks how to approve, shows the design and then the dashboards, and builds after each yes.", + "link": "The full example" + }, + "change": { + "label": "Change a solution", + "what": "Your agent adds a threshold to each freezer, an alarm that reads the threshold and a dashboard card to set the limit, then asks to deploy.", + "link": "Add alarms with your agent" + } + }, + "deploy": { + "title": "Deploy and open the dashboard", + "text": "Your agent asks before deploying, unless your request already says to. Pick “Deploy and stream live data” and open the dashboard link in the reply.", + "push-note": "A push replaces changes made in the ThingsBoard UI. Ask your agent to pull first.", + "stream": "Stream demo data again:" + }, + "connect-device": { + "title": "Connect your device", + "text": "After the deploy, your agent offers to connect a real device. Say Yes and name the device: an ESP32 board, a Raspberry Pi, or your own code. Your agent prepares the sketch, script or settings, then waits for the first value. No device yet? Say Later." + }, + "docs": { + "title": "Explore the docs", + "device": { + "title": "Connect a device", + "line": "HTTP, MQTT or CoAP, by firmware or script" + }, + "troubleshooting": { + "title": "Troubleshoot", + "line": "Connection, setup, push and demo data" + }, + "all": { + "title": "Browse all docs", + "line": "Alarms, customers, CI and the commands" + } + } + }, + "code": { + "script": "Script", + "lines": "{ count, plural, =1 {1 line} other {# lines} }", + "wrap-lines": "Wrap lines", + "one-line-each": "One line each", + "wrap-long-lines": "Wrap long lines", + "download": "Download", + "download-file": "Download {{name}}", + "label": { + "terminal": "Terminal", + "log": "Log", + "diff": "Diff", + "text": "Text", + "config": "Config" + } + }, + "task": { + "connect-device": { + "title": "Connect a device", + "hint": "A sensor, a gateway or a cloud integration", + "prompt": "Connect " + }, + "build-dashboard": { + "title": "Build a dashboard", + "hint": "From the keys a device sends", + "prompt": "Build a dashboard for " + }, + "set-up-alarm": { + "title": "Set up an alarm", + "hint": "A rule on a value, and who is told", + "prompt": "Alert me when " + } + }, + "copy": "Copy", + "edit-message": "Edit: the words back in the composer", + "show-all": "Show all", + "rename-save": "Save (Enter)", + "rename-discard": "Discard (Esc)", + "review": { + "verb": { + "install": "Install", + "restart": "Restart", + "update": "Update", + "upgrade": "Upgrade", + "upgrade-agent": "Upgrade the agent", + "delete": "Delete", + "cancel": "Cancel the operation", + "sync": "Sync" + }, + "head": { + "pending": "Needs your review", + "approved": "Approved", + "auto": "Auto-approved", + "denied": "Denied", + "expired": "No answer in time" + }, + "current": "Current", + "new": "New", + "unchanged": "{{count}} unchanged", + "hide-unchanged": "Hide unchanged", + "not-set": "not set", + "delete": "Delete", + "create": "Create", + "update": "Update", + "denied-text": "Nothing was made.", + "expired-text": "Nothing was made. The run waits here.", + "ask-again": "Ask again", + "ask-again-message": "Ask me again for the same change.", + "field": { + "integrationType": "Integration type", + "agent": "Agent", + "install": "Install", + "runs": "Runs", + "operation": "Operation", + "application": "Application", + "applications": "Applications", + "removeVolumes": "Delete its data", + "provisionType": "Provisioning", + "transport": "Transport", + "script": "Script", + "endpoint": "Endpoint", + "converter": "Converter", + "integration": "Integration", + "clientId": "Client ID", + "certificate": "Certificate", + "securityMode": "Security mode", + "entity": "Entity", + "appProfiles": "Application profiles", + "default": "Default profile", + "variant": "Variant", + "edgeTemplateRoot": "Root of new edges", + "autoAssign": "Assigned to new edges", + "cloudEndpoint": "Cloud endpoint", + "assign": "Assign", + "unassign": "Unassign", + "rootRuleChain": "Root rule chain", + "source": "Source", + "appTitle": "Title", + "platformName": "Platform name", + "logoImageUrl": "Logo", + "logoImageHeight": "Logo height", + "collapsedLogoImageUrl": "Collapsed logo", + "favicon": "Favicon", + "paletteSettings": "Colors", + "primaryColorPanels": "Colored panels", + "showNameVersion": "Show name and version", + "enableHelpLinks": "Help links", + "helpLinkBaseUrl": "Help links URL", + "customCss": "Custom CSS", + "pageBackgroundColor": "Page background", + "darkForeground": "Dark text", + "showNameBottom": "Name below the form", + "domain": "Domain", + "baseUrl": "Base URL", + "prohibitDifferentUrl": "Base URL only", + "subject": "Subject", + "useSystemTemplates": "Platform's templates", + "assignTo": "Assigned to", + "assignees": "Assignees", + "title": "Title", + "status": "Status", + "minVersion": "Minimum version", + "minVersionReleaseNotes": "Minimum version notes", + "latestVersion": "Latest version", + "latestVersionReleaseNotes": "Latest version notes", + "storeLink": "Store link", + "sha256CertFingerprints": "Certificate fingerprint", + "appId": "Apple app ID", + "appSecret": "App secret", + "androidAppId": "Android app", + "iosAppId": "iOS app", + "app": "App", + "bundleId": "Bundle", + "androidEnabled": "Android", + "iosEnabled": "iOS", + "showOnHomePage": "On the home page", + "badges": "Store badges", + "badgePosition": "Badge position", + "eventType": "Event type", + "target": "Target", + "schedule": "Schedule", + "method": "RPC method", + "params": "Parameters", + "oneway": "One-way", + "timeout": "Timeout, ms", + "persistent": "Persistent", + "package": "Package", + "enabled": "Enabled", + "methods": "Methods", + "issuerName": "Name in the app", + "smsTemplate": "SMS text", + "smsCodeLifetime": "SMS code valid, s", + "emailCodeLifetime": "Email code valid, s", + "backupCodes": "Backup codes", + "resendPeriod": "New code after, s", + "maxFailures": "Lockout after failures", + "totalTime": "Time to verify, s", + "checkRateLimit": "Code checks limit", + "oauth2Enabled": "OAuth 2.0", + "clients": "Sign-in buttons", + "warning": "Note", + "language": "Language", + "unitSystem": "Units", + "mainMethod": "Main method", + "apiKey": "API key", + "mailFrom": "Sender", + "smtpHost": "SMTP host", + "smtpPort": "SMTP port", + "smtpProtocol": "Protocol", + "enableTls": "TLS", + "username": "User name", + "password": "Password", + "enableProxy": "Proxy", + "proxyUser": "Proxy user", + "proxyPassword": "Proxy password", + "oauth2": "OAuth 2.0", + "test": "Test", + "useSystemSettings": "System settings", + "url": "URL", + "tag": "Tag", + "entities": "Entities", + "includes": "Also saves", + "removeOthers": "Delete what the version lacks", + "assignee": "Assignee", + "comment": "Comment", + "timeseries": "Telemetry", + "attributes": "Attributes", + "window": "Time window", + "type": "Type", + "dashboard": "Default dashboard", + "queue": "Queue", + "image": "Picture", + "value": "Value", + "provider": "Provider", + "model": "Model", + "credentials": "Credentials", + "hideToolbar": "Hide toolbar", + "repository": "Repository", + "branch": "Branch", + "authMethod": "Sign-in method", + "autoCommit": "Auto-commit", + "size": "Size", + "defaultDashboard": "Default dashboard", + "homeDashboard": "Home dashboard", + "email": "Email", + "firstName": "First name", + "lastName": "Last name", + "phone": "Phone", + "city": "City", + "address": "Address", + "user": "User", + "userGroups": "User groups", + "activation": "Activation", + "owner": "Owner", + "groups": "Groups", + "sharedWith": "Shared with", + "access": "Access", + "role": "Role", + "appliesTo": "Applies to", + "permissions": "Permissions", + "description": "Description", + "report-title": "Title", + "report-text": "Text", + "report-html": "Text", + "report-keys": "Keys", + "report-columns": "Columns", + "report-latestColumns": "Extra columns", + "report-series": "Series", + "report-key": "Key", + "report-timewindow": "Time window", + "report-thresholds": "Thresholds", + "report-legend": "Legend", + "report-axes": "Axes", + "report-height": "Height", + "report-chart": "Chart", + "report-url": "Image", + "report-templateId": "Sub-report", + "report-statuses": "Statuses", + "report-severities": "Severities", + "report-types": "Alarm types", + "report-sortOrder": "Sort order", + "report-states": "States", + "report-ranges": "Ranges", + "report-size": "Text size", + "report-bold": "Bold", + "report-italic": "Italic", + "report-color": "Color", + "report-align": "Alignment", + "report-verticalAlign": "Vertical alignment", + "report-keepTogether": "Keep together", + "report-units": "Units", + "report-decimals": "Decimals", + "reportTemplate": "Report template", + "reportUser": "Generated as", + "reportTimezone": "Report time zone", + "notificationTemplate": "Notification template", + "reportFor": "Generated for", + "report-settings": "Also changes", + "report-alias": "Entity alias", + "report-filter": "Filter", + "report-position": "Position", + "report-resolves": "Resolves to", + "report-conditions": "Conditions", + "report-name": "Name", + "report-description": "Description", + "report-format": "Format", + "report-page-size": "Page", + "report-page-orientation": "Orientation", + "report-page-margins": "Margins", + "report-page-background": "Page background", + "report-fileName": "File name", + "report-timeFormat": "Time format", + "report-header-enabled": "Header", + "report-header-firstPage": "First-page header", + "report-footer-enabled": "Footer", + "report-footer-firstPage": "First-page footer", + "widget-code": "Code", + "widget-type": "Widget type", + "widget-size": "Default size", + "widget-html": "HTML", + "widget-css": "CSS", + "widget-js": "JavaScript", + "widget-resources": "Resources", + "widget-settingsForm": "Settings form", + "widget-dataKeySettingsForm": "Data key settings form", + "widget-latestDataKeySettingsForm": "Latest data key settings form", + "widget-defaultConfig": "Default configuration", + "widget-tags": "Tags", + "widget-image": "Preview image", + "widget-deprecated": "Deprecated", + "widget-copyOf": "Copy of", + "widgetsBundle-order": "Order", + "widgetsBundle-widgets": "Widgets", + "widgetsBundle-image": "Image", + "scada-symbol": "Symbol", + "scada-family": "Family", + "scada-size": "Size", + "scada-behavior": "Behaviors", + "scada-properties": "Settings", + "scada-tags": "Search tags", + "scada-copyOf": "Copy of", + "scada-changed": "Changed", + "scada-bundle": "Bundle", + "format": "Format", + "templateType": "Template type", + "added": "Added", + "removed": "Removed", + "name": "Name", + "version": "Version", + "dependencies": "Also installs", + "label": "Label", + "profile": "Profile", + "arguments": "Arguments", + "expression": "Expression", + "output": "Output", + "severities": "Severities", + "clears": "Clears", + "undo": "Can be undone", + "template": "Template", + "recipients": "Recipients", + "delivery": "Delivery", + "when": "Sends at", + "slack": "Slack", + "mobileApp": "Mobile app", + "sms": "SMS", + "body": "Message", + "keys": "Keys", + "scope": "Scope", + "tlsVersion": "TLS version", + "passwordSecret": "Password from secret storage", + "proxyPasswordSecret": "Proxy password from secret storage" + }, + "value": { + "removeVolumes-yes": "Yes, for good", + "removeVolumes-no": "No, keep it", + "default-yes": "Yes", + "operation-restart": "Restart", + "operation-update": "Update to the profile", + "operation-upgrade": "Upgrade", + "operation-delete": "Delete", + "operation-cancel": "Cancel the running operation", + "operation-upgrade-agent": "Upgrade the agent", + "edgeTemplateRoot-yes": "Yes", + "autoAssign-yes": "Yes", + "autoAssign-no": "No", + "undo-none": "No: it is deleted for good", + "defaultDashboard-none": "None: the current one is cleared", + "homeDashboard-none": "None: the current one is cleared", + "clears-yes": "when its clear condition holds", + "clears-no": "only by hand", + "on": "on", + "off": "off", + "automatic": "automatic", + "set": "set", + "not-set": "not set", + "default": "Default" + }, + "detail": { + "server-attributes": "server attributes", + "shared-attributes": "shared attributes" + }, + "type": { + "IMAGE": "Image", + "VERSION": "Version", + "WHITE_LABELING": "White labeling", + "MAIL_TEMPLATE": "Mail template", + "CUSTOM_TRANSLATION": "Custom translation", + "CUSTOM_MENU": "Custom menu", + "MOBILE_APP": "Mobile app", + "MOBILE_BUNDLE": "Mobile bundle", + "MOBILE_QR_CODE": "Mobile app QR code", + "TWO_FACTOR_SETTINGS": "Security settings", + "MY_PROFILE": "Your profile", + "MY_TWO_FACTOR": "Your account security", + "MAIL_SERVER": "Mail server", + "RELATION": "Relations", + "PLATFORM_SETTINGS": "Platform settings", + "ENTITY_GROUP": "Group", + "ROLE": "Role", + "ALARM_RULE": "Alarm rule", + "DASHBOARD_WIDGET": "Widget", + "DASHBOARD_STATE": "Dashboard state", + "DASHBOARD_ENTITY_ALIAS": "Entity alias", + "DASHBOARD_FILTER": "Dashboard filter", + "REPORT_COMPONENT": "Report component", + "REPORT_ENTITY_ALIAS": "Report entity alias", + "REPORT_FILTER": "Report filter", + "SCHEDULED_REPORT": "Scheduled report", + "SCADA_SYMBOL": "SCADA symbol", + "NOTIFICATION": "Notification", + "NOTIFICATION_SETTINGS": "Notification delivery", + "NOTIFICATION_PREFERENCES": "Notification preferences" + } + }, + "record": { + "report": "Report", + "sub-report": "Sub-report", + "scheduled-report": "Scheduled report", + "group-of": "{{type}} group", + "on": "on {{name}}", + "on-profile": "on profile {{name}}", + "active": "Active", + "inactive": "Inactive", + "widgets": "{ count, plural, =1 {1 widget} other {# widgets} }", + "gateway": "Gateway", + "gateways": "Gateways", + "waiting-data": "Waiting for data", + "waiting-connect": "Waiting to connect", + "invited": "Invited", + "cleared": "Cleared", + "alarm-active": "Active", + "acknowledged": "Acknowledged", + "not-acknowledged": "Not acknowledged", + "since": "since {{time}}", + "cleared-at": "cleared {{time}}", + "installs": "{shown} { count, plural, =1 {install} other {installs} }", + "open-on-iot-hub": "Open on IoT Hub, in a new tab", + "open-new-tab": "Open the {{type}} in a new tab", + "open-type": "Open {{type}}", + "entity": "entity", + "install": "Install", + "install-on": "Install on…", + "install-on-prompt": "Install {{name}} on ", + "hub-items": "{ count, plural, =1 {1 IoT Hub item} other {# IoT Hub items} }", + "set-up-on": "Set up on" + }, + "summary": { + "made": "What this run made or changed", + "entities": "{ count, plural, =1 {1 entity} other {# entities} }", + "alarm-rules": "Alarm rules", + "more": "{{count}} more", + "fewer": "Fewer" + }, + "work": { + "reading-request": "Reading the request", + "going-through-results": "Going through the results", + "applying-change": "Applying the change", + "reading-what-to-change": "Reading what to change", + "estimate-minute": "about a minute", + "taking-longer": "taking longer than usual", + "more": "{{words}}, and {{count}} more", + "still": "Still {{words}}", + "stopped": "Stopped while {{words}}" + }, "file-kind": { "image": "Image", "pdf": "PDF", @@ -740,9 +2960,1399 @@ "text": "Text", "file": "File" }, - "rename-chat-title": "Rename this chat", - "export-chat": "Export chat", - "main-title": "Hello! I'm your AI Assistant" + "export-chat": "Export chat", + "chats": "Chats", + "open-chats": "Open chats", + "close-chats": "Close chats", + "search-chats": "Search chats", + "chats-found": "{ count, plural, =1 {1 chat} other {# chats} }", + "no-chat-matches": "No chat matches “{{query}}”.", + "chats-show-here": "Your chats show here.", + "chat-actions": "Chat actions", + "chat-title": "Chat title", + "prompt-placeholder": "Ask about your devices, dashboards and alarms, or connect something new…", + "what-to-work-on": "What would you like to work on?", + "pinned": "Pinned", + "pin": "Pin to the top", + "unpin": "Unpin", + "double-click-to-rename": "Double-click to rename", + "new-solution": "New solution", + "edit-design": "Edit the design", + "chats-menu": "Chats and this chat", + "resize-panel": "Resize the AI Assistant panel", + "resize-panel-hint": "Drag to resize; double-click to reset", + "open-full-screen": "Open full screen", + "recent-chats": "Recent chats", + "all-chats": "All chats", + "panel-title": "Ask about this page", + "panel-line": "What is on it, what to change, or something new.", + "intro": { + "lead-dashboard": "The chat opens beside the dashboard and sees what’s on it.", + "lead-dashboard-example": "The chat opens beside the dashboard and sees what’s on it. Try “{{example}}”.", + "lead-list": "The chat opens beside the list and sees what’s on it.", + "lead-list-example": "The chat opens beside the list and sees what’s on it. Try “{{example}}”.", + "lead-page": "The chat opens beside the page and sees what’s on it.", + "lead-page-example": "The chat opens beside the page and sees what’s on it. Try “{{example}}”.", + "keys": "Press / on any page to open the chat.", + "got-it": "Got it", + "open-chat": "Open the chat" + }, + "started-from": "Started from", + "open-page": "Open {{name}}", + "page": { + "DEVICE_LIST": "Devices", + "DEVICE_GROUP_LIST": "Device groups", + "DASHBOARD_LIST": "Dashboards", + "ALARM_LIST": "Alarms", + "ALARM_RULE_LIST": "Alarm rules", + "CALCULATED_FIELD_LIST": "Calculated fields", + "NOTIFICATION_TEMPLATE_LIST": "Notification templates", + "NOTIFICATION_RULE_LIST": "Notification rules", + "NOTIFICATION_RECIPIENT_LIST": "Notification recipients", + "SENT_NOTIFICATION_LIST": "Sent notifications", + "NOTIFICATION_INBOX": "Notification inbox", + "ASSET_LIST": "Assets", + "ASSET_GROUP_LIST": "Asset groups", + "ENTITY_VIEW_LIST": "Entity views", + "DEVICE_PROFILE_LIST": "Device profiles", + "ASSET_PROFILE_LIST": "Asset profiles", + "CUSTOMER_LIST": "Customers", + "USER_LIST": "Users", + "CUSTOMER_GROUP_LIST": "Customer groups", + "USER_GROUP_LIST": "User groups", + "ROLE_LIST": "Roles", + "RULE_CHAIN_LIST": "Rule chains", + "INTEGRATION_LIST": "Integrations", + "CONVERTER_LIST": "Converters", + "DASHBOARD_GROUP_LIST": "Dashboard groups", + "ENTITY_VIEW_GROUP_LIST": "Entity view groups" + }, + "copy-answer": "Copy the answer", + "feedback": { + "helpful": "Helpful", + "not-helpful": "Not helpful", + "report": "Report a problem", + "reported": "Reported", + "what-went-wrong": "What went wrong?", + "problem": { + "WRONG": "Wrong or made up", + "NOT_WHAT_I_ASKED": "Not what I asked", + "WRONG_CHANGE": "Changed the wrong thing", + "TOO_SLOW": "Too slow", + "OTHER": "Something else" + }, + "comment": "Anything to add (optional)", + "sent-with": "This answer and your words go to the ThingsBoard team.", + "send": "Send", + "thanks": "Thanks, the report is sent.", + "failed": "The feedback was not saved. Try again." + }, + "copied": "Copied", + "opens-new-tab": "(opens in a new tab)", + "what-should-be-different": "What should be different?", + "deny-placeholder": "Or say what should be different…", + "status-needs": "Needs you", + "status-nodata": "No data", + "status-running": "Running", + "status-error": "Failed", + "status-tip-needs": "Waits for your answer or approval", + "status-tip-nodata": "Nothing arrived from the device yet", + "status-tip-running": "In progress", + "status-tip-error": "The run stopped", + "waiting-one": "Open {{ title }}, which is waiting for you", + "waiting-one-tip": "{{ title }}: {{ status }}", + "waiting-many": "{ count, plural, =1 {1 chat needs you} other {# chats need you} }", + "running-one-tip": "{{ title }} is running", + "running-many": "{ count, plural, =1 {1 chat is running} other {# chats are running} }", + "stop": "Stop", + "stopped": "You stopped this reply. Nothing more was done.", + "auto-approve": "Auto-approve", + "auto-approve-on": "On", + "auto-approve-off": "Off", + "auto-approve-text": "Actions go ahead without waiting for your approval.", + "auto-approve-new-chat-text": "In the new chat, actions go ahead without waiting for your approval.", + "run-again": "Run again", + "fact": { + "pages": "{ count, plural, =1 {1 page} other {# pages} }", + "rows": "{ count, plural, =1 {1 row} other {# rows} }", + "columns": "{ count, plural, =1 {1 column} other {# columns} }", + "lines": "{ count, plural, =1 {1 line} other {# lines} }" + }, + "accept-suggestion": "Accept the suggestion", + "start-suggestion": "Connect a temperature sensor and chart its readings on a dashboard", + "suggestion-sr": "Suggestion: {{text}}. Tab accepts it.", + "file": { + "lines": "{ count, plural, =1 {1 line} other {# lines} }", + "open": "Open the file", + "wrap": "Wrap long lines", + "copy": "Copy the file", + "download": "Download", + "expand": "Expand the image", + "download-svg": "Download as SVG", + "download-png": "Download as PNG", + "png-failed": "The PNG could not be made from this image.", + "find": "Find in file", + "no-matches": "No matches", + "previous-match": "Previous match (Shift+Enter)", + "next-match": "Next match (Enter)", + "close-find": "Close (Esc)", + "more": "More: whitespace, theme", + "show-whitespace": "Show whitespace", + "theme": "Theme", + "dark": "Dark", + "light": "Light", + "line": "Line {{from}}", + "lines-range": "Lines {{from}}–{{to}}", + "clear": "Clear", + "ask-about": "Ask about them", + "files": "Files in this chat", + "files-in-chat": "{ count, plural, =1 {1 file in this chat} other {# files in this chat} }", + "unlist": "Remove from the list. The file stays in the chat.", + "unlist-ask": "Remove from the list?", + "unlist-do": "Remove from the list", + "keep": "Keep it", + "unlisted": "{{name}} removed from the list. It stays in the chat.", + "edit": "Edit", + "done": "Done", + "discard": "Discard", + "save": "Save", + "saved": "Saved", + "editing": "Editing", + "unsaved": "Unsaved changes", + "position": "Ln {{line}}, Col {{col}}", + "selected": "{{count}} selected", + "discarded": "Your changes to {{name}} were discarded.", + "editor": "Edit {{name}}", + "edited": "Edited", + "edited-in-chat": "Edited in this chat", + "marked": "marked", + "of-count": "of {{count}}", + "svg-broken": "This SVG does not draw. Edit opens its source." + }, + "welcome": { + "placeholder": "Ask anything or describe what to set up…", + "edges": { + "title": "Ask about your edges", + "title-customer": "Ask about this customer's edges", + "line": "Check which edges are connected, add one, or set up what each edge receives.", + "suggestion": "Which of my edges are offline?", + "example": { + "offline": { + "label": "Offline edges", + "message": "Which of my edges are offline, and since when?" + }, + "create": { + "label": "Add an edge", + "message": "Add a new edge and tell me how to install it with Docker." + } + } + }, + "edge": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this edge", + "line": "Its connection, what is assigned to it, and how to install or upgrade it.", + "suggestion": "Is this edge connected, and is anything waiting to reach it?", + "example": { + "status": { + "label": "Connection", + "message": "Is this edge connected, and are any downlinks failing?" + }, + "assign": { + "label": "What it receives", + "message": "What is assigned to this edge, and is anything missing?" + }, + "install": { + "label": "Install it", + "message": "How do I install this edge with Docker?" + } + } + }, + "edge-groups": { + "title": "Ask about your edge groups", + "title-customer": "Ask about this customer's edge groups", + "line": "Group edges, share them with customers, and check them together.", + "suggestion": "Which edge groups have offline edges?", + "example": { + "find": { + "label": "Offline edges", + "message": "Which edge groups have offline edges?" + } + } + }, + "edge-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this edge group", + "line": "Check its edges together.", + "suggestion": "Are all edges in this group connected?", + "example": { + "status": { + "label": "Connection", + "message": "Are all edges in this group connected?" + } + } + }, + "edge-scheduler": { + "title": "Ask about this edge's scheduler events", + "line": "Which scheduled events run on this edge.", + "suggestion": "Which scheduler events are assigned to this edge?", + "example": { + "assign": { + "label": "Assign an event", + "message": "Assign one of my scheduler events to this edge." + } + } + }, + "rule-chain-templates": { + "title": "Ask about your edge rule chains", + "line": "Add edge rule chains from IoT Hub, and choose which new edges get them.", + "suggestion": "Which rule chain does a new edge start with?", + "example": { + "root": { + "label": "New edges", + "message": "Which rule chains does a new edge get?" + }, + "hub": { + "label": "From IoT Hub", + "message": "Find an edge rule chain on IoT Hub for my use case." + } + } + }, + "rule-chain-template": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this edge rule chain", + "line": "Whether new edges get it, and which edges use it.", + "suggestion": "Which edges use this rule chain?", + "example": { + "edges": { + "label": "Edges using it", + "message": "Which edges use this rule chain?" + }, + "auto": { + "label": "New edges", + "message": "Assign this rule chain to every new edge." + } + } + }, + "integration-templates": { + "title": "Ask about your edge integrations", + "line": "Integrations that run on edges.", + "suggestion": "Which edges run my integration templates?", + "example": { + "edges": { + "label": "Where they run", + "message": "Which edges run my integration templates?" + } + } + }, + "integration-template": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this edge integration", + "line": "Which edges run it.", + "suggestion": "Which edges run this integration?", + "example": { + "edges": { + "label": "Where it runs", + "message": "Which edges run this integration?" + } + } + }, + "converter-templates": { + "title": "Ask about your edge converters", + "line": "Converters used by integrations on edges.", + "suggestion": "Which edge integrations use these converters?", + "example": { + "explain": { + "label": "Explain", + "message": "What do my edge converters do?" + } + } + }, + "converter-template": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this edge converter", + "line": "What it converts and where it is used.", + "suggestion": "What does this converter do?", + "example": { + "explain": { + "label": "Explain", + "message": "What does this converter do?" + } + } + }, + "agents": { + "title": "Ask about your agents", + "title-customer": "Ask about this customer's agents", + "line": "Agents run edges, gateways and other applications on your hosts.", + "suggestion": "Which agents are offline or have failing applications?", + "example": { + "status": { + "label": "Health", + "message": "Which agents are offline or have failing applications?" + }, + "deploy": { + "label": "Add an agent", + "message": "Add an agent and tell me how to install it on a Linux host." + } + } + }, + "agent": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this agent", + "line": "Its applications, their health, and upgrades.", + "suggestion": "Are all applications on this agent running?", + "example": { + "apps": { + "label": "Applications", + "message": "Are all applications on this agent running?" + }, + "edge": { + "label": "Run an edge", + "message": "Install an edge on this agent." + }, + "upgrade": { + "label": "Upgrade", + "message": "Is an upgrade available for this agent?" + } + } + }, + "agent-groups": { + "title": "Ask about your agent groups", + "title-customer": "Ask about this customer's agent groups", + "line": "Group agents and check them together.", + "suggestion": "Which agent groups have offline agents?", + "example": { + "find": { + "label": "Offline agents", + "message": "Which agent groups have offline agents?" + } + } + }, + "agent-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this agent group", + "line": "Check its agents together.", + "suggestion": "Are all agents in this group online?", + "example": { + "status": { + "label": "Health", + "message": "Are all agents in this group online?" + } + } + }, + "agent-applications": { + "title": "Ask about this agent's applications", + "line": "Install, restart, update or upgrade the applications it runs.", + "suggestion": "Are all applications on this agent running?", + "example": { + "status": { + "label": "Health", + "message": "Are all applications on this agent running?" + }, + "install": { + "label": "Install", + "message": "Install a gateway on this agent." + } + } + }, + "agent-application": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this application", + "line": "Its units, logs and recent operations.", + "suggestion": "Why did this application fail?", + "example": { + "logs": { + "label": "Why it failed", + "message": "Why did this application fail? Check its logs." + }, + "restart": { + "label": "Restart", + "message": "Restart this application." + } + } + }, + "agent-events": { + "title": "Ask about this agent's events", + "line": "Operations the agent ran and how they ended.", + "suggestion": "Which operations failed on this agent?", + "example": { + "failed": { + "label": "Failures", + "message": "Which operations failed on this agent, and why?" + } + } + }, + "agent-profiles": { + "title": "Ask about your agent profiles", + "line": "How agents provision, and which applications they install.", + "suggestion": "Which agent profile do new agents use?", + "example": { + "create": { + "label": "Add a profile", + "message": "Create an agent profile that installs an edge on every new agent." + }, + "default": { + "label": "Default", + "message": "Which agent profile do new agents use?" + } + } + }, + "agent-profile": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this agent profile", + "line": "Its applications, its agents and bulk updates.", + "suggestion": "Update the applications on every agent of this profile.", + "example": { + "apps": { + "label": "Applications", + "message": "Which applications does this profile install?" + }, + "bulk": { + "label": "Update all", + "message": "Update the applications on every agent of this profile." + } + } + }, + "agent-app-profiles": { + "title": "Ask about your application profiles", + "line": "Ready-made Edge, Gateway and other applications for your agents.", + "suggestion": "Create an Edge application profile.", + "example": { + "edge": { + "label": "Edge profile", + "message": "Create an Edge application profile." + }, + "gateway": { + "label": "Gateway profile", + "message": "Create a Gateway application profile." + } + } + }, + "agent-app-profile": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this application profile", + "line": "What it installs and which agent profiles use it.", + "suggestion": "What does this application profile install?", + "example": { + "explain": { + "label": "Explain", + "message": "What does this application profile install, and where is it used?" + } + } + }, + "agent-bulk-action": { + "title": "Ask about this bulk action", + "line": "Its progress on each agent.", + "suggestion": "How is this bulk action going?", + "example": { + "progress": { + "label": "Progress", + "message": "How is this bulk action going, and which agents failed?" + } + } + }, + "assets": { + "title": "Ask about your assets", + "line": "Their telemetry and alarms, or a dashboard to watch them.", + "suggestion": "Build a dashboard for my assets.", + "example": { + "find": {"label": "Find assets with alarms", "message": "Which of my assets have active alarms?"}, + "hierarchy": {"label": "Build a hierarchy", "message": "Create an asset for each of my buildings and put their devices under them."} + } + }, + "asset": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this asset", + "line": "Its telemetry, alarms and calculated fields, or a dashboard for it.", + "suggestion": "How is this asset doing?", + "example": { + "telemetry": {"label": "Show its latest telemetry", "message": "Show the latest telemetry of this asset."}, + "metric": {"label": "Add a calculated field", "message": "Add a calculated field to this asset."}, + "dashboard": {"label": "Build its dashboard", "message": "Build a dashboard for this asset."} + } + }, + "asset-groups": { + "title": "Ask about your asset groups", + "title-customer": "Ask about this customer's asset groups", + "line": "Watch a group's assets on a dashboard or set up alarms for them.", + "suggestion": "Build a dashboard for one of my asset groups.", + "example": { + "find": {"label": "Find groups with alarms", "message": "Which of my asset groups have assets with active alarms?"} + } + }, + "asset-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this asset group", + "line": "Its assets, how they are doing, or what to set up for all of them.", + "suggestion": "How are the assets in this group doing?", + "example": { + "status": {"label": "Check the group", "message": "How are the assets in this group doing?"} + } + }, + "entity-views": { + "title": "Ask about your entity views", + "line": "Their telemetry and alarms, or a dashboard to show them.", + "suggestion": "Build a dashboard for my entity views.", + "example": { + "find": {"label": "List my entity views", "message": "Which entity views do I have, and which entities do they show?"}, + "create": {"label": "Create a view", "message": "Create an entity view that shares only the temperature of one of my devices."} + } + }, + "entity-view": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this entity view", + "line": "Its telemetry and the entity it shows, or a dashboard for it.", + "suggestion": "Show the latest telemetry of this entity view.", + "example": { + "telemetry": {"label": "Show its latest telemetry", "message": "Show the latest telemetry of this entity view."}, + "source": {"label": "Find its entity", "message": "Which entity does this entity view show?"} + } + }, + "device-profiles": { + "title": "Ask about your device profiles", + "line": "Alarm rules and calculated fields for the devices of a profile.", + "suggestion": "Suggest alarm rules for my device profiles.", + "example": { + "find": {"label": "Find profiles without alarms", "message": "Which of my device profiles have no alarm rules?"} + } + }, + "device-profile": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this device profile", + "line": "Alarm rules and calculated fields for its devices.", + "suggestion": "Set up an alarm rule for this device profile.", + "example": { + "devices": {"label": "List its devices", "message": "Which devices use this profile?"}, + "alarm": {"label": "Set up an alarm", "message": "Set up an alarm rule for this device profile."}, + "metric": {"label": "Add a calculated field", "message": "Add a calculated field to this device profile."} + } + }, + "asset-profiles": { + "title": "Ask about your asset profiles", + "line": "Alarm rules and calculated fields for the assets of a profile.", + "suggestion": "Suggest alarm rules for my asset profiles.", + "example": { + "find": {"label": "Find profiles without alarms", "message": "Which of my asset profiles have no alarm rules?"}, + "create": {"label": "Create a profile", "message": "Create an asset profile for buildings with its own default dashboard."} + } + }, + "asset-profile": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this asset profile", + "line": "Alarm rules and calculated fields for its assets.", + "suggestion": "Set up an alarm rule for this asset profile.", + "example": { + "assets": {"label": "List its assets", "message": "Which assets use this profile?"}, + "alarm": {"label": "Set up an alarm", "message": "Set up an alarm rule for this asset profile."} + } + }, + "customers": { + "title": "Ask about your customers", + "line": "Add customers and their users, share devices and dashboards with them, or see how their equipment is doing.", + "suggestion": "Create customer bob@acme.com", + "example": { + "create": {"label": "Add a customer", "message": "Create a customer Acme with an administrator user bob@acme.com."}, + "find": {"label": "Find customers with alarms", "message": "Which customers have devices with active alarms?"} + } + }, + "customer": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this customer", + "line": "Its users, what it can see, its devices and dashboards.", + "suggestion": "Add a user to this customer", + "example": { + "user": {"label": "Add a user", "message": "Add a read-only user to this customer."}, + "share": {"label": "Share a dashboard", "message": "Share a dashboard with this customer, with the devices it shows."}, + "devices": {"label": "List its devices", "message": "Which devices does this customer own?"} + } + }, + "customer-groups": { + "title": "Ask about your customer groups", + "title-customer": "Ask about this customer's customer groups", + "line": "Group customers to manage them together, or see what each group holds.", + "suggestion": "Which customer groups do I have?", + "example": { + "create": {"label": "Create a group", "message": "Create a customer group for my retail customers."} + } + }, + "customer-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this customer group", + "line": "Its customers, or what to set up for all of them.", + "suggestion": "Which customers are in this group?", + "example": { + "list": {"label": "List its customers", "message": "Which customers are in this group?"} + } + }, + "users": { + "title": "Ask about your users", + "line": "Add users, give them the right access, or see who gets notified.", + "suggestion": "Add a user john@acme.com to customer Acme", + "example": { + "invite": {"label": "Add a user", "message": "Add a tenant administrator user."}, + "find": {"label": "Find who gets alarms", "message": "Which users receive alarm notifications?"} + } + }, + "user": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this user", + "line": "What this user can see and do, and the notifications it gets.", + "suggestion": "What can this user see and do?", + "example": { + "access": {"label": "Check their access", "message": "What can this user see and do?"}, + "notifications": {"label": "Notify this user", "message": "Notify this user when a critical alarm is raised."} + } + }, + "user-groups": { + "title": "Ask about your user groups", + "title-customer": "Ask about this customer's user groups", + "line": "Groups give users their roles: create one, or see what each can do.", + "suggestion": "What can the users in each group do?", + "example": { + "create": {"label": "Create a group", "message": "Create a user group of operators who can only see devices and send commands."} + } + }, + "user-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this user group", + "line": "Its users, the roles it gives, and what they apply to.", + "suggestion": "What can the users in this group do?", + "example": { + "access": {"label": "Check its access", "message": "What can the users in this group do?"}, + "add": {"label": "Add a user", "message": "Add a user to this group."} + } + }, + "roles": { + "title": "Ask about your roles", + "line": "What each role allows, or a new role for what your users need.", + "suggestion": "Which roles do I have, and what do they allow?", + "example": { + "create": {"label": "Create a role", "message": "Create a role that can see devices and dashboards but change nothing."}, + "explain": {"label": "Explain the roles", "message": "Which roles do I have, and what do they allow?"} + } + }, + "role": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this role", + "line": "What it allows, and who has it.", + "suggestion": "What does this role allow, and who has it?", + "example": { + "explain": {"label": "Explain it", "message": "What does this role allow, and who has it?"} + } + }, + "iot-hub": { + "title": "Find it ready-made in IoT Hub", + "line": "Widgets, calculated fields, alarm rules, rule chains and solution templates you can install in one step.", + "suggestion": "Find a widget that shows tank levels.", + "example": { + "popular": {"label": "Most popular", "message": "What are the most popular items in IoT Hub?"}, + "alarm": {"label": "Ready-made alarms", "message": "Find a ready-made alarm rule for low battery and install it on my devices."}, + "installed": {"label": "What's installed", "message": "What have I installed from IoT Hub, and are there updates?"} + } + }, + "rule-chains": { + "title": "What would you like to set up?", + "line": "Alarm rules, calculated fields, dashboards and notifications, or connecting a device.", + "suggestion": "Notify me when a critical alarm is raised.", + "example": { + "alarm": {"label": "Set up an alarm", "message": "Help me set up an alarm rule."}, + "notify": {"label": "Get notified", "message": "Notify me when a critical alarm is raised."} + } + }, + "integrations": { + "title": "Ask about your integrations", + "line": "Connect devices through an integration.", + "suggestion": "Help me connect a device through an integration.", + "example": { + "connect": {"label": "Connect a device", "message": "Help me connect a device through an integration."} + } + }, + "integration": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this integration", + "line": "Connect devices through it.", + "suggestion": "Help me connect a device through this integration.", + "example": { + "connect": {"label": "Connect a device", "message": "Help me connect a device through this integration."} + } + }, + "converters": { + "title": "Ask about your converters", + "line": "Connect devices through an integration and its converters.", + "suggestion": "Help me connect a device through an integration.", + "example": { + "connect": {"label": "Connect a device", "message": "Help me connect a device through an integration."} + } + }, + "converter": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this converter", + "line": "Connect devices through an integration that uses it.", + "suggestion": "Help me connect a device using this converter.", + "example": { + "connect": {"label": "Connect a device", "message": "Help me connect a device using this converter."} + } + }, + "dashboards": { + "title": "Ask about your dashboards", + "line": "Find one, build a new one, or change what it shows.", + "suggestion": "Build a dashboard for one of my devices", + "example": { + "build": {"label": "Build a dashboard", "message": "Build a dashboard for one of my devices with its latest telemetry, a chart and its active alarms."}, + "find": {"label": "Find a dashboard", "message": "Which of my dashboards show device telemetry?"} + } + }, + "dashboard": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this dashboard", + "line": "What is on it, what to change, or something new.", + "suggestion": "How is it doing?" + }, + "devices": { + "title": "Ask about your devices", + "line": "Find devices, check how they are doing, or connect a new one.", + "suggestion": "Which of my devices are inactive?", + "example": { + "inactive": {"label": "Find inactive devices", "message": "Which of my devices are inactive?"} + } + }, + "device": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this device", + "line": "Its telemetry, alarms and settings, or what to set up next.", + "suggestion": "How is this device doing?", + "example": { + "telemetry": {"label": "Show its latest telemetry", "message": "Show the latest telemetry of this device."}, + "alarm": {"label": "Set up an alarm", "message": "Set up an alarm rule for this device."}, + "dashboard": {"label": "Build its dashboard", "message": "Build a dashboard for this device."} + } + }, + "device-groups": { + "title": "Ask about your device groups", + "title-customer": "Ask about this customer's device groups", + "line": "What is in them, or how to organize your devices.", + "suggestion": "Which device groups do I have?" + }, + "device-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this device group", + "line": "Its devices, how they are doing, or what to set up for all of them.", + "suggestion": "How are the devices in this group doing?", + "example": { + "status": {"label": "Check the group", "message": "How are the devices in this group doing?"} + } + }, + "alarm-rules": { + "title": "Ask about your alarm rules", + "line": "Review them, find gaps, or add a new one.", + "suggestion": "Review my devices and suggest alarm rules worth setting up." + }, + "alarm-rule": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this alarm rule", + "line": "What it watches, when it fires, or how to change it.", + "suggestion": "Explain this alarm rule", + "example": { + "explain": {"label": "Explain this rule", "message": "Explain what this alarm rule watches and when it raises an alarm."} + } + }, + "alarms": { + "title": "Ask about your alarms", + "line": "What is active, why it fired, or what to do about it.", + "suggestion": "Which alarms need attention?", + "example": { + "attention": {"label": "What needs attention", "message": "Which alarms need attention right now?"}, + "triage": {"label": "Acknowledge the critical ones", "message": "Acknowledge all active critical alarms and tell me what caused them."} + } + }, + "alarm": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this alarm", + "line": "Why it fired, whether it still matters, and what to do with it.", + "suggestion": "Why was this alarm raised?", + "example": { + "explain": {"label": "Why it fired", "message": "Why was this alarm raised, and is the problem still there?"}, + "acknowledge": {"label": "Acknowledge it", "message": "Acknowledge this alarm and comment that I'm looking into it."} + } + }, + "calculated-fields": { + "title": "Ask about calculated fields", + "line": "What they compute, or a new one worth setting up.", + "suggestion": "Review my devices and suggest calculated fields worth setting up." + }, + "calculated-field": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this calculated field", + "line": "What it computes, or how to change it.", + "suggestion": "Explain this calculated field", + "example": { + "explain": {"label": "Explain this field", "message": "Explain what this calculated field computes and from which keys."} + } + }, + "notifications": { + "title": "Ask about notifications", + "line": "Who is told, about what, and how.", + "suggestion": "Explain how notifications work in ThingsBoard." + }, + "notification-template": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this notification template", + "line": "What it says, where it goes, and when it is used.", + "suggestion": "Explain what this template sends.", + "example": { + "explain": {"label": "Explain it", "message": "Explain what this template sends and through which channels."}, + "slack": {"label": "Add Slack", "message": "Also send this template's notifications to Slack."} + } + }, + "notification-rule": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this notification rule", + "line": "What triggers it, who is told, and how.", + "suggestion": "When does this rule fire?", + "example": { + "explain": {"label": "Explain it", "message": "When does this rule fire, and who is notified?"}, + "escalate": {"label": "Add escalation", "message": "Add an escalation to this rule if the alarm is not acknowledged in 15 minutes."} + } + }, + "notification-recipient": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this recipient group", + "line": "Who is in it and which rules notify it.", + "suggestion": "Which rules notify these recipients?", + "example": { + "rules": {"label": "Rules using it", "message": "Which notification rules send to these recipients?"} + } + }, + "dashboard-groups": { + "title": "Ask about your dashboard groups", + "title-customer": "Ask about this customer's dashboard groups", + "line": "Who can see which dashboards, and how to organize them.", + "suggestion": "Share a dashboard group with a customer.", + "example": { + "share": {"label": "Share a group", "message": "Share one of my dashboard groups with a customer, read-only."} + } + }, + "dashboard-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this dashboard group", + "line": "Its dashboards and who can open them.", + "suggestion": "Who can open the dashboards in this group?", + "example": { + "access": {"label": "Who can open it", "message": "Who can open the dashboards in this group?"} + } + }, + "entity-view-groups": { + "title": "Ask about your entity view groups", + "title-customer": "Ask about this customer's entity view groups", + "line": "What they expose, and to whom.", + "suggestion": "Which entity view groups do I have?" + }, + "entity-view-group": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this entity view group", + "line": "Its entity views and what they expose.", + "suggestion": "What do the entity views in this group show?", + "example": { + "list": {"label": "List its views", "message": "What do the entity views in this group show?"} + } + }, + "customer-hierarchy": { + "title": "Ask about your customer hierarchy", + "line": "Which customers sit under which, and what each one owns.", + "suggestion": "How are my customers organized?", + "example": { + "move": {"label": "Move a customer", "message": "Move a customer under another customer."} + } + }, + "gateways": { + "title": "Ask about your gateways", + "line": "Connect field devices through a gateway, or check how it is doing.", + "suggestion": "Which of my gateways are offline?", + "example": { + "modbus": {"label": "Connect Modbus devices", "message": "Help me connect Modbus devices through my gateway."}, + "status": {"label": "Check gateways", "message": "Which of my gateways are active, and what is connected to them?"} + } + }, + "ota-updates": { + "title": "Ask about firmware updates", + "line": "How OTA updates work, and how to roll one out.", + "suggestion": "How do I roll out new firmware to my devices?", + "example": { + "rollout": {"label": "Rollout status", "message": "How is the latest firmware rollout going?"}, + "add": {"label": "Add a package", "message": "Add firmware from a URL for one of my device profiles."} + } + }, + "white-labeling": { + "title": "Ask about white labeling", + "line": "Your logo, colors and title across the platform.", + "suggestion": "How do I change the logo and colors of the platform?", + "example": { + "brand": {"label": "Apply my brand", "message": "Use our brand color #0f7b6c and the title Acme IoT."} + } + }, + "login-white-labeling": { + "title": "Ask about the login page", + "line": "Its look, its domain, and what users see before they sign in.", + "suggestion": "How do I give the login page our own look?", + "example": { + "match": {"label": "Match the platform", "message": "Give the login page the same colors and logo as the platform."} + } + }, + "mail-templates": { + "title": "Ask about mail templates", + "line": "The emails the platform sends, such as activation and password reset.", + "suggestion": "Which emails can I change here?", + "example": { + "name": {"label": "Use our name", "message": "Put our company name Acme IoT instead of ThingsBoard in all emails."}, + "activation": {"label": "Friendlier activation email", "message": "Make the activation email shorter and friendlier, in our brand color #0f7b6c."} + } + }, + "custom-translation": { + "title": "Ask about custom translation", + "line": "Your own wording and languages for the platform.", + "suggestion": "How do I change a label in the UI for one language?", + "example": { + "rename": {"label": "Rename a word", "message": "Call devices \"machines\" in the menu and page titles."}, + "find": {"label": "What did we change?", "message": "Which texts have we customized so far?"} + } + }, + "custom-menu": { + "title": "Ask about custom menus", + "line": "Which menu items your users see, and where.", + "suggestion": "How do I hide menu items from a customer's users?", + "example": { + "simple": {"label": "Simpler menu for customers", "message": "Make a menu for customer users with only Home, Dashboards and Alarms."}, + "link": {"label": "Add a help link", "message": "Add a Help link to https://docs.example.com at the end of our menu."} + } + }, + "images": { + "title": "Ask about your images", + "line": "Images for dashboards, widgets and white labeling.", + "suggestion": "How do I use an image as a dashboard background?", + "example": { + "icon": {"label": "Draw an icon", "message": "Draw a simple pump icon and add it to my images."} + } + }, + "javascript-library": { + "title": "Ask about the JavaScript library", + "line": "Shared JavaScript modules for widgets and actions.", + "suggestion": "How do I use a JavaScript module in a widget?", + "example": { + "module": {"label": "Write a module", "message": "Write a JavaScript module with unit conversion helpers."} + } + }, + "resources-library": { + "title": "Ask about the resources library", + "line": "Files the platform uses, such as LwM2M models.", + "suggestion": "What can I keep in the resources library?" + }, + "two-factor-auth": { + "title": "Ask about two-factor authentication", + "line": "Which methods your users can use, and how to set them up.", + "suggestion": "How do I require two-factor authentication for my users?", + "example": { + "review": {"label": "Check our 2FA", "message": "Which two-factor methods are allowed, and is it enforced for anyone?"}, + "methods": {"label": "Allow app and backup codes", "message": "Let users verify only with an authenticator app or backup codes."}, + "enforce": {"label": "Require it for admins", "message": "How do I require two-factor authentication for tenant administrators?"} + } + }, + "oauth2-domains": { + "title": "Ask about OAuth 2.0 domains", + "line": "Which domains sign users in through an external provider.", + "suggestion": "How do I let users sign in with Google on my domain?", + "example": { + "missing": {"label": "Button not showing", "message": "Why is the Sign in with Google button missing on our login page?"}, + "hide": {"label": "Hide a sign-in button", "message": "Stop showing the GitHub sign-in button on our domain."} + } + }, + "oauth2-clients": { + "title": "Ask about OAuth 2.0 clients", + "line": "The external identity providers your users sign in with.", + "suggestion": "How do I set up sign-in with Microsoft Entra ID?", + "example": { + "review": {"label": "Review our clients", "message": "Which OAuth 2.0 clients do we have, and who gets an account through them?"} + } + }, + "self-registration": { + "title": "Ask about self-registration", + "line": "Let new users sign up on their own, and choose what they get.", + "suggestion": "How do I let customers sign up on their own?", + "example": { + "review": {"label": "Is sign-up safe?", "message": "Check our self-registration settings: is it on, and what do new users get?"} + } + }, + "secrets": { + "title": "Ask about secrets", + "line": "Keep credentials out of rule chains, integrations and settings.", + "suggestion": "How do I use a secret in a rule node?", + "example": { + "create": {"label": "Store a secret", "message": "Store an API key as a secret."} + } + }, + "audit-logs": { + "title": "Ask about the audit log", + "line": "Who changed what, and when.", + "suggestion": "What does the audit log record?", + "example": { + "changes": {"label": "Recent changes", "message": "What changed in the last 24 hours, and who did it?"}, + "logins": {"label": "Recent sign-ins", "message": "Who signed in today?"} + } + }, + "version-control": { + "title": "Ask about version control", + "line": "Keep your entities in Git and restore earlier versions.", + "suggestion": "How do I save my dashboards to Git?", + "example": { + "save": {"label": "Save a version", "message": "Save a version of all my dashboards."}, + "history": {"label": "Recent versions", "message": "What versions were saved this week, and by whom?"} + } + }, + "task-manager": { + "title": "Ask about the task manager", + "line": "Long-running jobs, such as reprocessing, and how they went.", + "suggestion": "What does the task manager show?", + "example": { + "failed": {"label": "Failed tasks", "message": "Which tasks failed recently, and why?"} + } + }, + "report-templates": { + "title": "Ask about your report templates", + "line": "Design PDF and CSV reports, or change an existing one.", + "suggestion": "Build a weekly PDF report of my devices.", + "example": { + "fleet": { + "label": "Weekly fleet report", + "message": "Build a weekly PDF report of my devices: a chart of their main readings over the previous week, a table of their latest values and their critical alarms." + }, + "export": { + "label": "Data export", + "message": "Make a CSV export of yesterday's telemetry of my devices, one row per hour." + } + } + }, + "report-template-new": { + "title": "Design this report", + "title-unnamed": "Design this report", + "line": "Say what it should show, for which devices and period, and how often it goes out.", + "suggestion": "Build a weekly PDF report of my devices." + }, + "scada-symbols": { + "title": "Ask about your SCADA symbols", + "line": "Find the right symbol for a process screen, or learn how one works.", + "suggestion": "Which symbols show a pump?", + "example": { + "find": { + "label": "Find a pump", + "message": "Which HP symbols show a pump, and what size are they?" + }, + "connectors": { + "label": "Joining pipes", + "message": "How do pipes and connectors join without a visible seam?" + } + } + }, + "scada-symbol": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this symbol", + "line": "What it shows, what its clicks do, and which values it reads.", + "suggestion": "What does this symbol show?", + "example": { + "explain": { + "label": "Explain it", + "message": "Explain what this symbol shows and what happens when it is clicked." + }, + "values": { + "label": "Its values", + "message": "Which values does this symbol read by default, and from where?" + } + } + }, + "widget-types": { + "title": "Ask about your widgets", + "line": "Write custom widgets for what the stock widgets can't show, or change your own.", + "suggestion": "Create a widget that shows a tank level.", + "example": { + "tank": { + "label": "Tank level widget", + "message": "Create a widget that shows a tank's fill level as a vertical tank with the percentage, red below 10 %." + }, + "heatmap": { + "label": "Weekly heatmap", + "message": "Create a chart widget that shows a key as a heatmap by hour of day and day of week." + } + } + }, + "widget-type": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this widget", + "line": "What it does, what to change, or why it breaks.", + "suggestion": "Check this widget for errors." + }, + "widget-type-new": { + "title": "Build this widget", + "title-unnamed": "Build this widget", + "line": "Say what it should show or do, and the assistant writes it and checks it in the preview.", + "suggestion": "Create a widget that shows a tank level." + }, + "widgets-bundles": { + "title": "Ask about your widgets bundles", + "line": "Group your widgets into bundles for the add-widget dialog.", + "suggestion": "Create a bundle for my custom widgets.", + "example": { + "custom": { + "label": "Bundle my widgets", + "message": "Create a bundle for my custom widgets and add them all to it." + } + } + }, + "widgets-bundle": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this widgets bundle", + "line": "Which widgets it holds, their order, or what to add.", + "suggestion": "Add my custom widgets to this bundle.", + "example": { + "add": { + "label": "Add my widgets", + "message": "Add my custom widgets to this bundle." + }, + "order": { + "label": "Sort the widgets", + "message": "Sort the widgets in this bundle by name." + } + } + }, + "report-template": { + "title": "Ask about {{name}}", + "title-unnamed": "Ask about this report template", + "line": "What is in it, what to change, or what to add.", + "suggestion": "Is this report ready to send?" + }, + "scheduled-reports": { + "title": "Ask about scheduled reports", + "line": "Send reports on a schedule: daily, weekly or monthly, to the people who need them.", + "suggestion": "Send my weekly report to the operations team every Monday.", + "example": { + "weekly": { + "label": "Weekly report every Monday", + "message": "Generate one of my report templates every Monday at 07:00 and send it to me." + }, + "next": { + "label": "What goes out next?", + "message": "Which reports are scheduled, when do they run next and who gets them?" + } + } + }, + "reports": { + "title": "Ask about your reports", + "line": "Find, get or clean up the reports generated so far, or generate one now.", + "suggestion": "Show me the latest report.", + "example": { + "latest": { + "label": "Latest report", + "message": "Show me the latest generated report in the chat." + }, + "now": { + "label": "Generate one now", + "message": "Generate a report from one of my templates now and keep it here." + } + } + }, + "scheduler": { + "title": "Ask about the scheduler", + "line": "Run actions on a schedule: update attributes, send commands, roll out firmware.", + "suggestion": "How do I send a command to my devices every night?", + "example": { + "night": {"label": "Night mode on weekdays", "message": "Every weekday at 22:00, set the shared attribute mode to night on my devices."}, + "week": {"label": "What runs this week?", "message": "Which scheduler events run in the next 7 days, and when?"} + } + }, + "home-settings": { + "title": "Ask about the home page", + "line": "Which dashboard your users see first.", + "suggestion": "How do I set a dashboard as the home page for my users?", + "example": { + "set": {"label": "Set the home page", "message": "Make one of my dashboards the home page for all users."} + } + }, + "mail-server-settings": { + "title": "Ask about your mail server", + "line": "How the platform sends email through your own server.", + "suggestion": "Set up sending email through my mail server.", + "example": { + "setup": {"label": "Set up email", "message": "Set up sending email through my mail server."}, + "check": {"label": "Is email working?", "message": "Which mail server do we send email through, and does it work? Send me a test email."} + } + }, + "notification-settings": { + "title": "Ask about notification delivery", + "line": "Slack, SMS, Microsoft Teams and the mobile app as ways to notify.", + "suggestion": "Connect Slack so I can get notifications there.", + "example": { + "slack": {"label": "Connect Slack", "message": "Connect Slack so I can get notifications there."}, + "sms": {"label": "Set up SMS", "message": "Set up SMS delivery for notifications."} + } + }, + "repository-settings": { + "title": "Ask about the Git repository", + "line": "Where version control keeps your entities.", + "suggestion": "How do I connect a GitHub repository?", + "example": { + "connect": {"label": "Connect GitHub", "message": "Connect a GitHub repository for version control."} + } + }, + "auto-commit-settings": { + "title": "Ask about auto-commit", + "line": "Which entities are saved to Git each time they change.", + "suggestion": "How does auto-commit work?", + "example": { + "devices": {"label": "Auto-commit devices", "message": "Commit every device change to Git automatically."} + } + }, + "ai-models": { + "title": "Ask about AI models", + "line": "The models that rule nodes and other features use.", + "suggestion": "How do I add an OpenAI model?", + "example": { + "add": {"label": "Add a model", "message": "Add an OpenAI model for my rule chains."} + } + }, + "api-usage": { + "title": "Ask about API usage", + "line": "What your tenant uses, against its limits.", + "suggestion": "What do these API usage numbers mean?", + "example": { + "limits": {"label": "Check my limits", "message": "Am I close to any of my limits this month?"} + } + }, + "mobile-bundles": { + "title": "Ask about mobile bundles", + "line": "Your mobile app's layout, sign-in and branding.", + "suggestion": "How do I set up a mobile app for my customers?", + "example": { + "dashboard": {"label": "Add a dashboard to the app", "message": "Add one of my dashboards to the mobile app menu, right after Home."}, + "review": {"label": "What do users see?", "message": "Which pages does our mobile app menu show?"} + } + }, + "mobile-apps": { + "title": "Ask about mobile apps", + "line": "The Android and iOS apps that connect to the platform.", + "suggestion": "How do I connect my own mobile app?", + "example": { + "release": {"label": "New release", "message": "We released version 1.4.0 of our app; make everyone below 1.2.0 update."}, + "register": {"label": "Register our app", "message": "Register our Android app com.acme.iot."} + } + }, + "account-profile": { + "title": "Ask about your profile", + "line": "Your name, language, units and the dashboard you start on.", + "suggestion": "Show temperatures in Fahrenheit", + "example": { + "home": {"label": "Start on a dashboard", "message": "Open my main dashboard right after I sign in."}, + "units": {"label": "Switch units", "message": "Switch my units to imperial."} + } + }, + "account-security": { + "title": "Ask about your account security", + "line": "Your two-factor methods, API keys and password.", + "suggestion": "How do I set up an authenticator app?", + "example": { + "review": {"label": "Check my security", "message": "How is my account protected, and what should I improve?"}, + "keys": {"label": "Review my API keys", "message": "Which API keys do I have, and are any of them unused or expired?"} + } + }, + "account-notifications": { + "title": "Ask about your notifications", + "line": "Which notifications you get, and where.", + "suggestion": "Stop emailing me about device activity", + "example": { + "quiet": {"label": "Fewer emails", "message": "Only email me about alarms; keep everything else in the bell."}, + "review": {"label": "What do I get?", "message": "Which notifications do I get, and by which methods?"} + } + }, + "mobile-qr-code": { + "title": "Ask about the mobile QR code", + "line": "The QR code that opens the mobile app on your platform.", + "suggestion": "How do users sign in with the QR code?", + "example": { + "home": {"label": "Show it on Home", "message": "Show the mobile app QR code on the home page with the label Get the app."} + } + }, + "trendz": { + "title": "Ask about Trendz Analytics", + "line": "Analytics, predictions and anomaly detection on your data.", + "suggestion": "What can Trendz do with my data?" + } + }, + "artifact": { + "close": "Close the panel (Esc)", + "resize": "Resize the panel", + "resize-hint": "Drag to resize; double-click to reset" + }, + "plan": { + "title": "Plan", + "steps": "{ count, plural, =1 {1 step} other {# steps} }", + "done-of": "{{done}} of {{count}}", + "change": "Change the plan", + "change-ask": "Change the plan.", + "you": "You", + "needs": { + "device": "Requires device", + "account": "Requires account", + "computer": "Requires computer", + "phone": "Requires phone" + }, + "run": "Run", + "run-step-by-step": "Run step by step", + "run-auto": "Run with auto-approve", + "run-tip": "Each change waits for your approval", + "run-auto-tip": "Changes are made as the plan says. Every action still shows, and Stop halts the run.", + "run-prompt": "Run the plan.", + "leave-out": "Leave out step {{number}}: {{text}}" + }, + "offer": { + "label": "Auto-approve offer", + "text": "The rest of this run waits for your yes at each step. Let it run through? Every action still shows here, and Stop halts the run.", + "approve-rest": "Auto-approve the rest", + "keep-asking": "Keep asking" + }, + "list": { + "pair": "{{first}} and {{second}}", + "more": "{{first}}, {{rest}}" + }, + "part": { + "html": "HTML", + "css": "CSS", + "js": "JavaScript", + "resources": "resources", + "settingsForm": "settings form", + "dataKeySettingsForm": "data key settings form", + "latestDataKeySettingsForm": "latest data key settings form", + "defaultConfig": "default configuration", + "svg": "SVG", + "metadata": "metadata", + "functions": "functions", + "behavior": "behaviors", + "properties": "properties" + }, + "part-title": { + "html": "HTML", + "css": "CSS", + "js": "JavaScript", + "resources": "Resources", + "settingsForm": "Settings form", + "dataKeySettingsForm": "Data key settings form", + "latestDataKeySettingsForm": "Latest data key settings form", + "defaultConfig": "Default configuration", + "svg": "SVG", + "metadata": "Metadata", + "functions": "Functions", + "behavior": "Behaviors", + "properties": "Properties" + }, + "duration": { + "seconds": "{{seconds}} s", + "minutes": "{{minutes}} min", + "minutes-seconds": "{{minutes}} min {{seconds}} s" + } }, "alarm": { "alarm": "Alarm", @@ -2527,8 +6137,10 @@ "display-dashboard-export": "Display export", "display-update-dashboard-image": "Display update dashboard image", "display-configure-with-ai": "Display \"Configure with AI\" button", + "ai-assistant-title": "Ask about this dashboard", "ai-assistant-initial-prompt-placeholder": "Describe what you'd like to set up...", "ai-assistant-example-monitor-device-label": "Monitor a device", + "ai-assistant-suggestion": "How is it doing?", "ai-assistant-example-monitor-device-message": "The device is ... I want to set up this dashboard as a single-state view of it, showing its latest telemetry as value cards at the top, a time series chart of that telemetry below them, and a table of its active alarms at the bottom.", "ai-assistant-example-monitor-fleet-label": "Monitor a device fleet", "ai-assistant-example-monitor-fleet-message": "The device type is ... I want to set up this dashboard with two states for it. The overview state should list all devices of that type in an entities table, with a table of active alarms for those devices below it. Selecting a device opens a details state showing that device's latest telemetry as value cards at the top, a time series chart of that telemetry below them, and a table of its active alarms at the bottom.", @@ -2707,6 +6319,7 @@ "device": { "ai-assistant-initial-prompt-placeholder": "Describe what you'd like to set up...", "ai-assistant-example-connect-label": "Connect my device", + "ai-assistant-suggestion": "Which of my devices are inactive?", "ai-assistant-example-connect-message": "Help me connect one of my devices to the platform so it starts sending real telemetry.", "all": "All", "all-devices": "All devices", @@ -5326,6 +8939,414 @@ "show-help": "Show help" }, "home": { + "iot-hub": { + "search": "Search IoT Hub", + "open-results": "Open results in IoT Hub", + "all-devices": "All {{count}} devices", + "also": "Also in IoT Hub", + "unavailable": "IoT Hub is not available right now.", + "templates": "Solution templates", + "device-library": "Device library", + "widgets": "Widgets", + "calculated-fields": "Calculated fields", + "alarm-rules": "Alarm rules", + "rule-chains": "Rule chains" + }, + "status": { + "critical-alarms": "{ count, plural, =1 {1 critical alarm} other {# critical alarms} }", + "active-alarms": "{ count, plural, =1 {1 active alarm, none critical} other {# active alarms, none critical} }", + "no-alarms": "No active alarms", + "inactive-devices": "{ count, plural, =1 {1 device inactive} other {# devices inactive} }", + "device-active": "Device active", + "all-devices-active": "All {{count}} devices active", + "nothing-assigned": "No devices or dashboards assigned to you yet", + "system-ok": "CPU, RAM and disk under 75%", + "system-high": "{{name}} at {{value}}%", + "system-high-on": "{{name}} at {{value}}% on {{service}}", + "system-high-services": "{{name}} at {{value}}% on {{count}} services", + "license-near": "License: {{items}}", + "license-devices": "devices {{percent}}%", + "license-assets": "assets {{percent}}%", + "license-ai-credits": "AI credits {{percent}}%", + "no-tenants": "No tenants yet", + "features-off": "{ count, plural, =1 {1 feature not configured} other {# features not configured} }" + }, + "greeting": { + "morning": "Good morning", + "afternoon": "Good afternoon", + "evening": "Good evening", + "morning-name": "Good morning, {{name}}", + "afternoon-name": "Good afternoon, {{name}}", + "evening-name": "Good evening, {{name}}" + }, + "cards": { + "iot-hub": "IoT Hub", + "alarms": "Alarms", + "dashboards": "Dashboards", + "devices": "Devices", + "activity": "Activity", + "get-started": "Get started", + "notifications": "Notifications", + "quick-links": "Quick links", + "usage": "Usage", + "mobile-app": "Mobile app", + "product-release": "Product release", + "system-status": "System", + "license": "License", + "install-items": "Install" + }, + "alarms": { + "whose": "Whose alarms", + "all": "All", + "mine": "Mine", + "add-rule": "Add alarm rule", + "no-rules": "No alarm rules yet. Add a rule to see its alarms here.", + "how-rules-work": "How alarm rules work", + "no-alarms-yet": "No alarms yet", + "view-cleared": "View cleared", + "show-only": "Show {{severity}} only", + "show-every": "Show every severity", + "severity": "Severity", + "type": "Type", + "originator": "Originator", + "started": "Started", + "started-at": "Started {{time}}", + "assignee": "Assignee", + "ack": "Ack", + "sort-severity": "Sort by severity", + "sort-started": "Sort by start time", + "assigned-you": "Assigned to you", + "assigned-to": "Assigned to {{name}}", + "not-assigned": "Not assigned", + "assign-me": "Assign to me", + "acknowledge": "Acknowledge", + "acknowledged-tip": "Acknowledged", + "not-acknowledged": "Not acknowledged", + "open-details": "Open details", + "clear": "Clear", + "clear-title": "Clear {{name}}?", + "clear-text": "The alarm leaves the active list. To see it later, filter Alarms by Cleared.", + "actions": "Alarm actions", + "name": "{{type}} on {{originator}}", + "acknowledged": "{{name}} acknowledged", + "assigned": "{{name}} assigned to you", + "cleared": "{{name}} cleared", + "none-active": "No active alarms.", + "none-mine": "No alarms assigned to you.", + "none-severity": "No {{severity}} alarms.", + "none-severity-mine": "No {{severity}} alarms assigned to you." + }, + "dashboards": { + "view": "Dashboards view", + "last-viewed": "Last viewed", + "starred": "Starred", + "add": "Add dashboard", + "name": "Name", + "star": "Star {{title}}", + "unstar": "Unstar {{title}}", + "star-tip": "Star", + "unstar-tip": "Unstar", + "none": "No dashboards yet. Add a dashboard to open it from here.", + "none-assigned": "No dashboards assigned to you yet", + "from-template": "Start from a template", + "how-to": "How to build dashboards", + "none-viewed": "No dashboards viewed yet.", + "none-starred": "No starred dashboards yet.", + "star-a-dashboard": "Star a dashboard", + "all-starred": "Every dashboard is starred", + "search-to-star": "Search dashboards to star", + "no-match": "No dashboards match “{{query}}”.", + "starred-toast": "“{{title}}” starred", + "opens-new-tab": "(opens in a new tab)" + }, + "devices": { + "add": "Add device", + "none": "No devices yet. Add a device to see its state here.", + "none-assigned": "No devices assigned to you yet", + "how-to": "How to connect a device", + "inactive": "Inactive", + "active": "Active", + "show-only-inactive": "Show inactive only", + "show-only-active": "Show active only", + "show-every": "Show all devices", + "one-active": "The device is active.", + "all-active": "All {{count}} devices are active.", + "name": "Name", + "profile": "Device profile", + "state": "State", + "last-activity": "Last activity", + "last-activity-at": "Last activity {{time}}", + "sort-name": "Sort by name", + "sort-last": "Sort by last activity", + "never": "never", + "no-data": "No data received yet", + "none-inactive": "No inactive devices.", + "none-active": "No active devices." + }, + "activity": { + "period": "Last 30 days", + "series": "Activity series", + "devices": "Active devices", + "messages": "Messages", + "today": "Today", + "none": "No activity yet", + "no-messages": "No messages from devices yet" + }, + "get-started": { + "progress": "{{done}} of {{total}}", + "all-done": "All done", + "step-of": "Step {{step}} of {{total}}", + "guide": "Guide", + "open": "Open {{page}}", + "done": "Done", + "done-aria": "Done: {{title}}", + "mark-done": "Mark as done", + "mark-undone": "Mark as not done", + "start-over": "Start over", + "started-over": "Get started is back to its first step", + "alarm-rules": "Alarm rules", + "add-device": { + "title": "Add a device", + "text": "Add a device on the Devices page and copy its access token." + }, + "send-value": { + "title": "Send the first value", + "text": "Run this with the device's access token in place of $ACCESS_TOKEN." + }, + "add-dashboard": { + "title": "Add a dashboard", + "text": "Add a dashboard and a widget that shows the device's temperature." + }, + "add-alarm-rule": { + "title": "Add an alarm rule", + "text": "Add a rule that raises an alarm when the temperature goes above 25 °C." + }, + "raise-alarm": { + "title": "Raise the alarm", + "text": "Send a value above 25 °C to raise the alarm." + }, + "share": { + "title": "Share with a customer", + "text": "Add a customer and assign the dashboard. The customer's users see only what is assigned to them." + } + }, + "notifications": { + "none": "No unread notifications.", + "show-full": "Show the full notification", + "marked-read": "Notification marked as read", + "marked-all-read": "{{count}} notifications marked as read" + }, + "quick-links": { + "edit": "Edit quick links", + "edit-link": "Edit {{name}}", + "remove": "Remove {{name}}", + "none": "No quick links yet. Add the pages and links you open often.", + "add": "Add link", + "full": "{{max}} links, the most this card holds. Remove one to add another.", + "reset": "Reset to defaults", + "reset-done": "Quick links reset to the defaults", + "drag-hint": "Drag rows to reorder", + "added": "\"{{name}}\" added to quick links", + "removed": "\"{{name}}\" removed from quick links", + "saved": "\"{{name}}\" saved", + "opens-new-tab": "(opens in a new tab)", + "documentation": "Documentation", + "user-guide": "User guide", + "getting-started": "Getting started", + "tenant-profiles": "Tenant profiles", + "api": "API", + "widgets-library": "Widgets library", + "add-title": "Add quick link", + "edit-web-link": "Edit web link", + "link-type": "Link type", + "page": "Page", + "web-link": "Web link", + "pages": "Pages", + "search-pages": "Search pages", + "added-mark": "Added", + "no-pages": "No matches. To link to another site, use Web link.", + "address": "Address", + "name": "Name", + "name-placeholder": "Shown in the list", + "icon": "Icon", + "search-icons": "Search icons", + "loading-icons": "Loading icons…", + "no-icons": "No icons match \"{{query}}\".", + "icons-more": "{{total}} icons. Showing the first {{shown}}; refine the search to see others.", + "icons-count": "{ count, plural, =1 {1 icon} other {# icons} }", + "opens-host": "Opens {{host}} in a new tab", + "only-web": "Only web addresses (http or https) can be added.", + "full-address": "Enter a full web address, for example docs.example.com.", + "trust": "A web link opens another site. Add only sites you trust.", + "insecure": "This address is not encrypted (http). Use https if the site supports it." + }, + "usage": { + "view": "Usage view", + "of-limit": "{{percent}}% of limit", + "no-limit": "No limit" + }, + "mobile-app": { + "qr": "QR code to connect the mobile app", + "download-on-the": "Download on the", + "get-it-on": "Get it on" + }, + "release": { + "available": "Update available", + "title": "ThingsBoard {{version}} is available", + "read-notes": "Read the release notes before upgrading.", + "notes": "Release notes", + "upgrade": "Upgrade", + "hide": "Hide", + "hidden": "{{version}} hidden" + }, + "get-started-sys-admin": { + "before-tenants": "Before tenants sign in", + "when-needed": "When you need them", + "progress": "{{done}} of {{total}}", + "tenants": "{ count, plural, =1 {1 tenant} other {# tenants} }", + "configured": "Configured", + "skipped": "Skipped", + "skip": "Skip", + "undo-skip": "Undo skip", + "finished": "Every step is done. The Install card takes this place.", + "finished-skipped": "{{count}} skipped. The Install card takes this place, and each skipped feature stays there to set up.", + "tenant": { + "title": "Create a tenant and its administrator", + "text": "A tenant owns devices and assets; its administrators create and manage its devices, assets, customers and dashboards.", + "action": "Add tenant" + }, + "email": { + "title": "Mail server", + "text": "Mail server configuration is essential for user activation, password recovery, and alarm notification delivery.", + "action": "Open Mail server" + }, + "sms": { + "title": "SMS provider", + "text": "Configure SMS providers to notify the customers about the alarms via SMS.", + "action": "Open Notifications settings" + }, + "wl": { + "title": "White labeling", + "text": "Customize your company's or product's logo and color scheme without coding and without restarting the service.", + "action": "Open White labeling" + }, + "2fa": { + "title": "Two-factor authentication (2FA)", + "text": "Improve security of the platform accounts with two-factor authentication.", + "action": "Open Two-factor authentication" + }, + "oauth": { + "title": "OAuth 2.0 single sign-on", + "text": "Simplify login for the tenant and customer users with Single Sign-On functionality via OAuth 2.0.", + "action": "Open OAuth 2.0" + }, + "slack": { + "title": "Slack", + "text": "Distribute notifications to the tenant and customer users via Slack according to the notification rules you set.", + "action": "Open Notifications settings" + } + }, + "license": { + "development-mode": "Development mode", + "development-line": "Non-production use only. Limits do not apply; White labeling is not available.", + "updated-tooltip": "When the license info was last read from the License Portal", + "devices-and-assets": "Devices and assets", + "installations": "Installations", + "this-month": "This month", + "of-limit": "{{percent}}% of your limit", + "at-limit": "At your limit", + "not-in-license": "Not in your license", + "go-to-production": "Go to production", + "see-plans": "See plans", + "production-use": "Production use", + "production-use-text": "Real devices and customers on this install.", + "ai-credits-text": "A monthly pool for the AI Assistant across the install.", + "add-ons-text": "Edge Computing and Trendz Analytics, added to the license." + }, + "install": { + "add-tenant": "Add tenant", + "tenants": "Tenants", + "tenant-profiles": "Tenant profiles", + "users": "Users", + "customers": "Customers", + "dashboards": "Dashboards", + "integrations": "Integrations", + "features": "Features", + "checking": "Checking the configuration", + "features-count": "{{on}} of {{total}}", + "white-labeling": "White labeling", + "mail-server": "Mail server", + "sms-provider": "SMS provider", + "slack": "Slack", + "oauth": "OAuth 2.0", + "two-fa": "2FA", + "configured": "configured", + "not-configured": "not configured" + }, + "system": { + "last-hour": "Last hour", + "services": "{ count, plural, =1 {1 service} other {# services} }", + "version": "ThingsBoard {{version}}", + "release-notes": "Release notes of {{version}}", + "available": "{{version}} available", + "show-update": "Show the update again", + "cores": "{ count, plural, =1 {1 core} other {# cores} }", + "gb": "{{value}} GB", + "at": "{{name}} at {{value}}%", + "at-on": "{{name}} at {{value}}% on {{services}}", + "and": "{{first}} and {{second}}", + "now": "now", + "chart": "CPU, RAM and disk over the last hour", + "service-id": "Service ID", + "service-type": "Service type" + }, + "list": { + "show-more": "Show more", + "show-all": "Show all", + "show-less": "Show less", + "shown-of": "{{shown}} of {{total}}", + "view-all": "View all" + }, + "ago": { + "now": "now", + "min": "{{count}} min ago", + "hour": "{{count}}h ago", + "day": "{{count}}d ago", + "week": "{{count}}w ago" + }, + "elapsed": { + "now": "now", + "min": "{{count}} min", + "hour": "{{count}}h", + "day": "{{count}}d", + "week": "{{count}}w" + }, + "ai": { + "placeholder": "Ask the AI Assistant…", + "chats": "Chats", + "waiting": "Waiting for you", + "waiting-tip": "{{tip}}, {{ago}}", + "start-title": "Get started with AI", + "start-device": "Connect a device", + "start-device-tip": "The AI Assistant's Get started: one device, from an example", + "start-solution": "Create a solution", + "start-solution-tip": "The AI Assistant's New solution: describe it, or start from an example", + "start-cli": "Use the CLI", + "start-cli-tip": "Opens the ThingsBoard CLI guide for your coding agent", + "offer-title": "Ask from Home", + "offer-text": "Ask a question, or have it connect a device, build a dashboard or add an alarm rule.", + "offer-action": "Ask", + "offer-key": "{{key}} to ask" + }, + "customize": { + "title": "Customize Home", + "show-on-home": "Show on Home", + "show-all": "Show all", + "cards": "Cards on Home", + "hide": "Hide {{name}}", + "hidden": "{{name}} hidden", + "undo": "Undo" + }, "home": "Home", "profile": "Profile", "logout": "Logout", @@ -7277,6 +11298,7 @@ "addon-access-error": "Add-on/Feature access error", "addon-access-request": "Add-on/Feature access request", "plan-upgrade-request": "Plan upgrade request", + "ai-credits-limit-increase-request": "AI credits limit increase request", "entity-action": "Entity action", "general": "General", "integration-lifecycle-event": "Integration lifecycle event", @@ -9144,6 +13166,22 @@ "copy-public-link": "Copy link" }, "report-template": { + "ai-reload-title": "The AI changed this template", + "ai-reload-text": "Load the AI's version? Your unsaved changes will be lost.", + "ai-reload-keep": "Keep my changes", + "ai-reload-confirm": "Load the AI's version", + "ai-assistant-title": "Ask about this report template", + "ai-assistant-initial-prompt-placeholder": "Describe the report you need…", + "ai-assistant-suggestion": "Is this report ready to send?", + "ai-assistant-example-fleet-label": "Weekly fleet report", + "ai-assistant-example-fleet-message": "Build a weekly PDF report of my devices: a chart of their main readings over the previous week, a table of their latest values and their critical alarms.", + "ai-assistant-example-export-label": "Data export", + "ai-assistant-example-export-message": "Make a CSV export of yesterday's telemetry of my devices, one row per hour.", + "ai-assistant-example-check-label": "Check the report", + "ai-assistant-example-check-message": "Generate a test report and tell me what is wrong or empty in it.", + "ai-assistant-example-per-device-label": "One section per device", + "ai-assistant-example-per-device-message": "Give every device its own section with its chart and table, each starting on a new page.", + "new-report-template-name": "New report template", "report-template": "Report template", "report-templates": "Report templates", "add": "Add report template", @@ -10014,6 +14052,152 @@ "background-color": "Background color", "background-blur": "Background blur" }, + "tour": { + "invite": { + "pill-before": "Meet the new AI Assistant", + "pill-new": "Meet the AI Assistant", + "news": "A working setup in minutes.", + "cover-title": "Just ask.", + "cover-lead": "The AI Assistant sets up devices, builds dashboards and writes alarm rules. Ask about your data and it explains what changed and why.", + "note": "The AI solution creator has moved to the AI Assistant.", + "kicker-before": "What's new", + "kicker-new": "How it works", + "kicker": "{{kicker}} · {{step}} of {{count}}", + "step": "Step {{step}} of {{count}}", + "go-before": "See what's new", + "go-new": "See how it works", + "later": "Maybe later", + "back": "Back", + "next": "Next", + "show-around": "Show me around", + "card-1": { + "title": "Start here", + "lead": "The new Home opens on what needs a decision: critical alarms, devices gone quiet, chats waiting for you. Ask about any of it from the same page." + }, + "card-2": { + "title": "Ask on any page", + "lead": "The chat sits next to your page and reads it. Say “this meter” and it knows which one." + }, + "card-3": { + "title": "Describe the result, not the steps", + "lead": "One sentence becomes a plan: the dashboard, the alarm rule, who gets notified. Changes wait for your approval." + }, + "card-4": { + "title": "Click, don’t type", + "lead": "A threshold, a color, which device: pick from the options. Type only when none fits." + }, + "card-5": { + "title": "Files in. Files out.", + "lead": "Attach a datasheet, a photo or a spreadsheet. Code, configs and documents come back as files to open, edit and download." + } + }, + "scene": { + "cover": { + "placeholder": "What would you like to work on?", + "ask-1": "What needs my attention today?", + "reply-1": "Two alarms are critical, both in Store 7.", + "record-1-name": "Freezer 2 · Store 7", + "record-1-meta": "critical for 18 min", + "ask-2": "Build a dashboard for the Store 12 freezers", + "reply-2": "Three freezers, their temperatures and doors.", + "record-2-name": "Store 12 freezers", + "record-2-meta": "Dashboard · created", + "ask-3": "Connect the sensor in this datasheet", + "file-3-name": "SHT31 datasheet.pdf", + "file-3-meta": "PDF", + "reply-3": "Temperature and humidity, read from page 3." + }, + "home": { + "ask": "Which devices are inactive?", + "morning": "Good morning", + "afternoon": "Good afternoon", + "evening": "Good evening", + "critical": "3 critical alarms", + "inactive": "4 devices inactive", + "placeholder": "Ask the AI Assistant…", + "chats": "Chats", + "waiting": "Waiting for you", + "chat-1": "Cold room sensors", + "chat-2": "Gateway on the store PC", + "alarms": "Alarms", + "notifications": "Notifications" + }, + "page": { + "ask": "Why did this meter jump at 02:00?", + "load": "Load now", + "today": "Today", + "alarm": "Night load above 8 kW", + "title": "Ask about this dashboard", + "prompt-2": "Add the freezer doors to this chart", + "answer": "Freezer 2 has run nonstop since 01:52. Its door was left open.", + "record-name": "Freezer 2 · Store 12", + "record-meta": "door open 3 h", + "page": "Energy · Store 12", + "range": "Last 6 hours", + "new-chat": "New chat" + }, + "plan": { + "request": "A dashboard for the Store 12 freezers, an alarm when one gets warm, and tell the store manager", + "plan": "Plan", + "steps": "3 steps", + "run": "Run", + "running": "Running", + "done": "Done", + "row-1": "Store 12 freezers", + "row-2": "Freezer too warm", + "row-3": "Tell the manager", + "dashboard": "Dashboard", + "alarm-rule": "Alarm rule", + "notification-rule": "Notification rule", + "planned": "{{type}} · planned", + "created": "{{type}} · created" + }, + "ask": { + "needs-answer": "Needs an answer", + "count-1": "1 of 2", + "count-2": "2 of 2", + "question-1": "Who gets the alert?", + "why-1": "An email when a freezer stays warm.", + "option-1-1": "Me", + "option-1-2": "The store manager", + "option-1-3": "Both", + "other": "Other…", + "hint-1": "The manager is at the store when it happens", + "next": "Next", + "skip": "Skip", + "said": "Who gets the alert", + "question-2": "How warm is too warm?", + "why-2": "Freezer 1 reads −18.4 °C now.", + "option-2-1": "−15 °C", + "option-2-2": "−14 °C", + "option-2-3": "−12 °C", + "hint-2": "So a short door opening won’t trigger it", + "done": "Done" + }, + "files": { + "in": "In", + "out": "Out", + "edit": "Edit" + } + }, + "assistant": { + "count": "{{step}} of {{count}}", + "skip": "Skip tour", + "next": "Next", + "done": "Done", + "menu-title": "AI Assistant in the menu", + "menu-text": "Your chats and solutions live here. On any other page, the AI Assistant button in the top bar opens the same chats beside the page.", + "chats-title": "All chats in one list", + "chats-text": "Chats started here, on Home or beside any page. A dot marks a chat that waits for your answer.", + "chats-folded-text": "Open the list here: chats started here, on Home or beside any page.", + "solutions-title-before": "AI solution creator moved here", + "solutions-text-before": "Click New solution to start one. Each solution is a chat in this list, with its design and installation beside it, as before.", + "solutions-title-new": "Build a whole solution", + "solutions-text-new": "Click New solution and describe a use case. After a few questions, a design of profiles, dashboards and alarm rules opens beside the chat, to review and install.", + "start-title": "Your first chat", + "start-text": "Describe what you’re building or the device you have. Or pick an example below and edit it before you send." + } + }, "unit": { "set-unit-conversion": "Set unit conversion", "unit-settings": { @@ -10790,6 +14974,20 @@ "generate-report-canceled": "Generate report canceled" }, "widget": { + "ai-assistant-title": "Ask about this widget", + "ai-assistant-initial-prompt-placeholder": "Describe the widget you need…", + "ai-assistant-suggestion": "Check this widget for errors.", + "ai-assistant-example-explain-label": "Explain this widget", + "ai-assistant-example-explain-message": "Explain what this widget does: its data, settings and how it renders.", + "ai-assistant-example-setting-label": "Add a setting", + "ai-assistant-example-setting-message": "Add a settings option for the value color.", + "ai-assistant-example-check-label": "Check for errors", + "ai-assistant-example-check-message": "Check this widget for errors and fix them.", + "ai-assistant-example-tank-label": "Tank level widget", + "ai-assistant-example-tank-message": "Make this a widget that shows a tank's fill level as a vertical tank with the percentage, red below 10 %.", + "ai-assistant-example-status-label": "Status card", + "ai-assistant-example-status-message": "Make this a card that shows whether a device is online, with a colored dot and the time of its last activity.", + "new-widget-name": "New widget", "widget-library": "Widgets library", "widget-bundle": "Widgets Bundle", "all-bundles": "All bundles", @@ -11340,47 +15538,152 @@ "select-recaptcha-enterprise-service-account-file": "Drag and drop your account credentials file" }, "solution-creator": { - "ai-solution-creator": "AI solution creator", + "opening": "Opening the solution…", + "stopped": "You stopped this step. Nothing was changed.", + "pane": { + "alarms": "Alarms", + "attribute": "attribute", + "calculated-fields": "Calculated fields", + "calculates": "Calculates", + "creating": "Creating…", + "dashboards": "Dashboards", + "data": "Data", + "description": "Description", + "designing": "Designing…", + "estimate-overview": "About 30 seconds", + "estimate-dashboards": "About 30 seconds", + "estimate-solution": "About a minute", + "about-seconds": "About {{count}} seconds", + "about-minutes": "About {{count}} minutes", + "credits": "{credits} { count, plural, =1 {credit} other {credits} }", + "get-started": "Get started", + "installed": "Solution installed", + "installed-line": "{ entities, plural, =1 {1 entity} other {# entities} } · { dashboards, plural, =1 {1 dashboard} other {# dashboards} } · live on simulated data", + "view-as-user": "View as {{name}}", + "json-note": "Edits here are applied as they are; the AI does not review them.", + "json-invalid": "Not valid JSON: {{message}}", + "json-applied": "Applied", + "json-discarded": "Your JSON changes were discarded.", + "json-tip": "View as JSON", + "view-json": "View", + "keys": "{ count, plural, =1 {1 key} other {# keys} }", + "list": "List", + "list-or-schema": "List or schema", + "name": "Name", + "no-alarms": "No alarm rules in this design.", + "no-calculated-fields": "No calculated fields in this design.", + "no-dashboards": "No dashboards yet.", + "no-keys": "No keys.", + "no-relations": "No relations.", + "no-roles": "No roles in this design.", + "nothing-created": "Nothing is created yet.", + "not-installed": "The solution is created but not installed. Install it to make its entities in your tenant.", + "on": "On", + "op-create": "Create", + "op-read": "Read", + "op-update": "Update", + "op-delete": "Delete", + "open": "Open", + "operations": "Operations", + "profiles": "Profiles", + "relations": "{ count, plural, =1 {1 relation} other {# relations} }", + "relations-tab": "Relations", + "remove": "Remove", + "role": "Role", + "roles": "Roles", + "schema": "Schema", + "scope": "Scope", + "sections": "Sections", + "severity": "Severity", + "solution": "Solution", + "status-ok": "Created", + "status-warn": "Created, not connected", + "status-wait": "Up next", + "status-now": "Being created", + "alarm-rules": "Alarm rules", + "alarm-rule": "Alarm rule", + "view-as-main": "View as user", + "install-failed": "Install failed", + "step-failed": "Step failed", + "open-name": "Opens {{name}}", + "open-list": "Opens {{name}} in ThingsBoard", + "pending-DEVICE": "{{profile}} devices", + "pending-ASSET": "{{profile}} assets", + "pending-CUSTOMER": "{{profile}} customers", + "pending-USER": "{{profile}} users", + "status-error": "Not created", + "telemetry": "Telemetry", + "time-series": "time series", + "type": "Type", + "view": "View", + "view-overview": "Overview", + "view-dashboards": "Dashboards", + "view-solution": "Solution", + "view-as": "View as" + }, + "view-as-name": "View as {{name}}", + "connect-devices": "Connect real devices", + "uninstalled-at": "Uninstalled at {{time}}.", + "uninstalled-note": "The entities are removed; the design is kept. Create solution installs it again.", + "installed-already": "Installed already.", + "installed-already-note": "The installed solution stays as it is until you create it again; creating then replaces it.", + "what-should-it-do": "What should the solution do?", + "what-it-becomes": "A description becomes profiles, roles, calculated fields, alarm rules and dashboards, on simulated devices.", + "example-tip": "Puts the example in the composer", + "limits": "Nothing is created in your tenant until you approve the design and install it.", + "what-is-solution": "What is a solution?", + "about-title": "AI solution creator", + "about-design-title": "A description becomes a design", + "about-design": "The AI drafts the architecture: device and asset profiles, relations, roles, calculated fields and alarm rules.", + "about-approve-title": "You approve each step", + "about-approve": "Change anything in the chat, regenerate, then go on. Nothing is created until you say so.", + "about-dashboards-title": "Dashboards come with it", + "about-dashboards": "Every role gets its dashboard; simulated devices feed them until yours connect.", + "about-installed-title": "Installed in your tenant", + "about-installed": "Real entities, yours to keep: edit the design or uninstall it from the solution's chat.", + "issues-lead": "{ count, plural, =1 {One item needs your attention} other {# items need your attention} } after the install:", + "issues-tip-lead": "Tip:", + "issues-tip": "open the Solution view to see what went wrong with each, or ask about it here.", + "assumptions": "Assumptions", + "next-dashboards-note": "Say what to change, or go on to the dashboards.", + "next-create": "Say what to change, or create the solution.", + "type-the-answer": "Or type the answer here…", + "say-what-to-change": "Say what to change in the design…", + "ask-about-solution": "Ask about the solution…", + "next-dashboards": "Next: dashboards", + "closing-installed": "The solution is installed in your tenant.", + "closing-created": "The solution is created. Install it to make its entities in your tenant.", + "installed-made": { + "device": "{ count, plural, =1 {1 device} other {# devices} }", + "asset": "{ count, plural, =1 {1 asset} other {# assets} }", + "profile": "{ count, plural, =1 {1 profile} other {# profiles} }", + "calculated-field": "{ count, plural, =1 {1 calculated field} other {# calculated fields} }", + "alarm-rule": "{ count, plural, =1 {1 alarm rule} other {# alarm rules} }", + "role": "{ count, plural, =1 {1 role} other {# roles} }", + "user": "{ count, plural, =1 {1 user} other {# users} }", + "dashboard": "{ count, plural, =1 {1 dashboard} other {# dashboards} }" + }, + "installed-summary": "Solution installed: {{items}}.", + "installed-and": "and", + "shared-with": "shared with {{name}}", + "closing-simulated-lead": "Simulated data runs for seven days.", + "closing-simulated": "A real device takes over a simulated one when it connects.", + "work-reading": "Reading your description", + "work-thinking": "Working on the design", "describe-solution-you-want": "Describe a solution you want to make", - "enter-your-prompt": "Enter your prompt", "target": "Target", "install-solution": "Install", - "solution-overview": "Solution overview: {{ name }}", - "dashboards-overview": "Dashboards overview: {{ name }}", - "entity-profile": "Entity profile", - "entity-profiles": "Entity profiles", - "name": "Name", - "iam": "IAM", - "iam-full": "Identity and Access Management", - "table-view": "Table", - "schema-view": "Schema", - "iam-info": "IAM info", "operation": { "C": "Create", "R": "Read", "U": "Update", "D": "Delete" }, - "alarm-info": "Alarm info", "description": "Description", - "data": "Data", - "entity-info": "Entity info", - "calculated-field-info": "Calculated field info", - "field-type": "Field type", - "scope": "Scope", "delete-alarm-title": "Delete this suggested alarm?", "delete-alarm-text": "This alarm, suggested based on your description, won't be added to the proposed solution build.
You can always edit or recreate alarms manually later. This action cannot be undone.", - "basic-mode": "Basic", - "advanced-mode": "Advanced", "create-solution": "Create solution", "go-dashboard-manager": "Next: Dashboard Design", - "success-generate-title": "Solution is ready!", - "success-generate-sub-title": "You can install it on your account by clicking the button below", - "success-generate-install-title": "Solution installed!", - "success-generate-install-sub-title": "To edit the solution, please uninstall the existing instance first", - "main-title": "Hello! I'm your AI Assistant", - "sub-title": "I help you transform your requirements into a fully functional IoT solution.\nJust describe what you want to achieve, and I'll handle the rest.", - "solutions": "Solutions", "new-solution": "New solution", "uninstall-solution": "Uninstall", "uninstall-solution-dialog-title": "Are you sure you want to uninstall ‘{{ name }}’?", @@ -11390,12 +15693,9 @@ "delete-solution-text": "All your data will be lost", "delete-solution-confirm": "Yes, delete", "copy-solution": "Copy solution", - "expand-sidebar": "Expand sidebar", - "collapse-sidebar": "Collapse sidebar", "solution-id": "Solution id", "solution-id-required": "Solution id is required", - "rename-solution-title": "Rename this solution", - "generate-again": "Generate again", + "regenerate": "Regenerate", "skip-interview": "Skip interview", "update-solution": "Update solution", "finish-edit": "Finish edit", @@ -11405,8 +15705,6 @@ "water-metering": "Water Metering", "coffee-machine-monitoring": "Coffee Machine Monitoring", "fleet-geofencing": "Fleet Geofencing", - "more-examples": "More examples", - "hide": "Hide", "solution-info": "Solution info", "solution-info-with-name": "Solution info: {{ name }}", "status": "Status", @@ -11419,14 +15717,8 @@ "info": "Info", "main-dashboard": "Main dashboard", "view-as": "View as {{ name }}", - "generated-by-calculated-field-name": "Generated by ‘{{ name }}’ calculated field", "estimate-wait-time": "Estimated wait time is ~{{ time }}", - "analyzing-your-request": "Analyzing your request...", "condition": "Condition", - "installing": "Installing solution...", - "step-architecture-design": "Architecture Design", - "step-dashboard-design": "Dashboard Design", - "step-solution-installation": "Solution Installation", "step-reading-device-data": "Reading device data…", "step-analyzing-telemetry-attributes": "Analyzing telemetry & attributes…", "step-selecting-widgets": "Selecting widgets for your data…", @@ -11458,11 +15750,7 @@ "step-loading-building-alarm-rules": "Building alarm rules…", "step-loading-assembling-dashboards": "Assembling dashboards…", "step-loading-preparing-states": "Preparing states…", - "step-loading-initializing-solution": "Initializing solution…", - "ai-credits": "AI Credits", - "ai-credits-update": "Update", - "ai-credits-usage": "AI Credits: {{ used }} of {{ max }} used", - "ai-credits-description": "You've used {{ used }} of your {{ max }} AI Credits this month. Limit resets on {{ date }}. To increase your AI Credit allowance, please contact your system administrator." + "step-loading-initializing-solution": "Initializing solution…" }, "markdown": { "edit": "Edit", @@ -13901,11 +18189,6 @@ "disk-warning-text": "Running low on disk space. To avoid data loss, free up or expand the disk space.", "disk-critical-text": "Critically low disk space. To avoid data loss, free up or expand the disk space." }, - "cluster-info": { - "service-id": "Service id", - "service-type": "Service type", - "no-data": "No data" - }, "transport-messages": { "title": "Transport messages", "info": "All the messages that came from devices" @@ -13944,41 +18227,9 @@ "no-last-viewed-dashboards": "No last viewed dashboards yet" }, "configured-features": { - "title": "Configured features", - "info": "Status of features that require configuration", - "white-labeling-feature": "White labeling", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Feature is configured.\nClick to setup", "feature-not-configured": "Feature is not configured.\nClick to setup" }, - "version-info": { - "title": "Version", - "contact-us": "Contact us", - "current-version": "Current version", - "current": "Current", - "available-version": "Available version", - "available": "Available", - "upgrade": "Upgrade", - "version-is-up-to-date": "Version is up to date" - }, - "license-info": { - "title": "License info", - "view-all": "View all", - "license-portal": "License portal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Devices", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrations", - "community-support": "Community support", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Unlimited datapoints and messages", - "unlimited-api-calls": "Unlimited API calls" - }, "usage-info": { "title": "Usage", "entities": "Entities", diff --git a/ui-ngx/src/assets/locale/locale.constant-es_ES.json b/ui-ngx/src/assets/locale/locale.constant-es_ES.json index ae7b5bc9f7..d7359fb705 100644 --- a/ui-ngx/src/assets/locale/locale.constant-es_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-es_ES.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurar con IA", - "follow-up-prompt-placeholder": "Responder...", - "sub-title": "Puedo ayudarte a configurar y gestionar tus dispositivos, paneles, campos calculados, reglas de alarma y notificaciones; solo describe lo que necesitas y yo me encargo del resto.", "new-chat": "Nuevo chat", - "no-chats": "Aún no hay chats", "today": "Hoy", "yesterday": "Ayer", "last-7-days": "Últimos 7 días", @@ -703,18 +700,12 @@ "delete-chat-title": "¿Estás seguro de que quieres eliminar '{{name}}'?", "delete-chat-text": "Se perderán todos los mensajes del chat", "delete-chat-confirm": "Sí, eliminar", - "action-approval-required": "Se requiere aprobación de la acción", "approve": "Aprobar", - "approve-all": "Aprobar todas las acciones siguientes", "deny": "Denegar", - "processing": "Procesando...", "approved": "Hecho", - "denied": "Denegado", "error": "Falló", "thinking": "Pensando...", - "rename-chat-title": "Cambiar el nombre de este chat", - "export-chat": "Exportar chat", - "main-title": "¡Hola! Soy tu asistente de IA" + "export-chat": "Exportar chat" }, "alarm": { "alarm": "Alarma", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Arrastra y suelta tu archivo de credenciales de cuenta" }, "solution-creator": { - "ai-solution-creator": "Creador de soluciones con IA", "describe-solution-you-want": "Describe la solución que deseas crear", - "enter-your-prompt": "Ingresa tu instrucción", "target": "Destino", "install-solution": "Instalar", - "solution-overview": "Resumen de la solución: {{ name }}", - "dashboards-overview": "Resumen de tableros: {{ name }}", - "entity-profile": "Perfil de entidad", - "entity-profiles": "Perfiles de entidad", - "name": "Nombre", - "iam": "IAM", - "iam-full": "Gestión de identidades y accesos", - "table-view": "Tabla", - "schema-view": "Esquema", - "iam-info": "Información de IAM", "operation": { "C": "Crear", "R": "Leer", "U": "Modificar", "D": "Eliminar" }, - "alarm-info": "Información de la alarma", "description": "Descripción", - "data": "Datos", - "entity-info": "Información de la entidad", - "calculated-field-info": "Información del campo calculado", - "field-type": "Tipo de campo", - "scope": "Ámbito", "delete-alarm-title": "¿Eliminar esta alarma sugerida?", "delete-alarm-text": "Esta alarma, sugerida a partir de tu descripción, no se agregará a la compilación de la solución propuesta.
Siempre puedes editar o volver a crear las alarmas manualmente más tarde. Esta acción no se puede deshacer.", - "basic-mode": "Básico", - "advanced-mode": "Avanzado", "create-solution": "Crear solución", "go-dashboard-manager": "Siguiente: Diseño del tablero", - "success-generate-title": "¡La solución está lista!", - "success-generate-sub-title": "Puedes instalarla en tu cuenta haciendo clic en el botón de abajo", - "success-generate-install-title": "¡Solución instalada!", - "success-generate-install-sub-title": "Para editar la solución, primero desinstala la instancia existente", - "main-title": "¡Hola! Soy tu asistente de IA", - "sub-title": "Te ayudo a transformar tus requisitos en una solución IoT totalmente funcional.\nSolo describe lo que deseas lograr y yo me encargo del resto.", - "solutions": "Soluciones", "new-solution": "Nueva solución", "uninstall-solution": "Desinstalar", "uninstall-solution-dialog-title": "¿Estás seguro de que deseas desinstalar ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Se perderán todos tus datos", "delete-solution-confirm": "Sí, eliminar", "copy-solution": "Copiar solución", - "expand-sidebar": "Expandir barra lateral", - "collapse-sidebar": "Contraer barra lateral", "solution-id": "ID de la solución", "solution-id-required": "Se requiere el ID de la solución", - "rename-solution-title": "Cambiar el nombre de esta solución", - "generate-again": "Generar de nuevo", "skip-interview": "Omitir entrevista", "update-solution": "Actualizar solución", "finish-edit": "Finalizar edición", @@ -11298,8 +11258,6 @@ "water-metering": "Medición de agua", "coffee-machine-monitoring": "Monitoreo de máquinas de café", "fleet-geofencing": "Geocercas para flotas", - "more-examples": "Más ejemplos", - "hide": "Ocultar", "solution-info": "Información de la solución", "solution-info-with-name": "Información de la solución: {{ name }}", "status": "Estado", @@ -11312,14 +11270,8 @@ "info": "Información", "main-dashboard": "Tablero principal", "view-as": "Ver como {{ name }}", - "generated-by-calculated-field-name": "Generado por el campo calculado ‘{{ name }}’", "estimate-wait-time": "El tiempo de espera estimado es de ~{{ time }}", - "analyzing-your-request": "Analizando tu solicitud...", "condition": "Condición", - "installing": "Instalando la solución...", - "step-architecture-design": "Diseño de la arquitectura", - "step-dashboard-design": "Diseño del tablero", - "step-solution-installation": "Instalación de la solución", "step-reading-device-data": "Leyendo los datos del dispositivo…", "step-analyzing-telemetry-attributes": "Analizando telemetría y atributos…", "step-selecting-widgets": "Seleccionando widgets para tus datos…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construyendo reglas de alarma…", "step-loading-assembling-dashboards": "Ensamblando tableros…", "step-loading-preparing-states": "Preparando estados…", - "step-loading-initializing-solution": "Inicializando la solución…", - "ai-credits": "Créditos de IA", - "ai-credits-update": "Guardar cambios", - "ai-credits-usage": "Créditos de IA: {{ used }} de {{ max }} utilizados", - "ai-credits-description": "Has utilizado {{ used }} de tus {{ max }} créditos de IA este mes. El límite se restablece el {{ date }}. Para aumentar tu asignación de créditos de IA, contacta a tu administrador del sistema." + "step-loading-initializing-solution": "Inicializando la solución…" }, "markdown": { "edit": "Editar", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Espacio en disco reducido. Para evitar pérdida de datos, libere o expanda el espacio.", "disk-critical-text": "Espacio en disco críticamente bajo. Para evitar pérdida de datos, libere o expanda el espacio." }, - "cluster-info": { - "service-id": "ID del servicio", - "service-type": "Tipo de servicio", - "no-data": "Sin datos" - }, "transport-messages": { "title": "Mensajes de transporte", "info": "Todos los mensajes que llegaron desde los dispositivos" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Aún no se han visualizado tableros recientemente" }, "configured-features": { - "title": "Características configuradas", - "info": "Estado de las características que requieren configuración", - "white-labeling-feature": "Marca blanca", - "email-feature": "Correo electrónico", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "La característica está configurada.\nHaz clic para configurarla", "feature-not-configured": "La característica no está configurada.\nHaz clic para configurarla" }, - "version-info": { - "title": "Versión", - "contact-us": "Contáctenos", - "current-version": "Versión actual", - "current": "Actual", - "available-version": "Versión disponible", - "available": "Disponible", - "upgrade": "Actualizar versión", - "version-is-up-to-date": "La versión está actualizada" - }, - "license-info": { - "title": "Información de licencia", - "view-all": "Ver todo", - "license-portal": "Portal de licencias", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivos", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Activos", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Tableros", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraciones", - "community-support": "Soporte comunitario", - "white-labeling": "Marca blanca", - "unlimited-datapoints-and-messages": "Puntos de datos y mensajes ilimitados", - "unlimited-api-calls": "Llamadas API ilimitadas" - }, "usage-info": { "title": "Uso", "entities": "Entidades", diff --git a/ui-ngx/src/assets/locale/locale.constant-fa_IR.json b/ui-ngx/src/assets/locale/locale.constant-fa_IR.json index d639e90e19..69a9e18198 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fa_IR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fa_IR.json @@ -88,10 +88,7 @@ }, "ai-assistant": { "configure-with-ai": "پیکربندی با هوش مصنوعی", - "follow-up-prompt-placeholder": "پاسخ...", - "sub-title": "می‌توانم در راه‌اندازی و مدیریت دستگاه‌ها، داشبوردها، فیلدهای محاسبه‌شده، قوانین هشدار و اعلان‌های شما کمک کنم — کافی است آنچه نیاز دارید را توضیح دهید و بقیه را به من بسپارید.", "new-chat": "گفت‌وگوی جدید", - "no-chats": "هنوز گفت‌وگویی وجود ندارد", "today": "امروز", "yesterday": "دیروز", "last-7-days": "7 روز گذشته", @@ -99,16 +96,11 @@ "delete-chat-title": "آیا مطمئن هستید که می‌خواهید '{{name}}' را حذف کنید؟", "delete-chat-text": "همه پیام‌های گفت‌وگو از دست خواهند رفت", "delete-chat-confirm": "بله، حذف کن", - "action-approval-required": "تأیید اقدام لازم است", "approve": "تأیید", "deny": "رد", - "processing": "در حال پردازش...", "approved": "انجام شد", - "denied": "رد شد", "error": "ناموفق", - "thinking": "در حال فکر کردن...", - "rename-chat-title": "تغییر نام این گفت‌وگو", - "main-title": "سلام! من دستیار هوش مصنوعی شما هستم" + "thinking": "در حال فکر کردن..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "پیشنهاد قوانین هشدار", diff --git a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json index a9b8fd88ee..87b321a794 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurer avec l’IA", - "follow-up-prompt-placeholder": "Répondre...", - "sub-title": "Je peux vous aider à configurer et à gérer vos appareils, tableaux de bord, champs calculés, règles d’alarme et notifications — décrivez simplement ce dont vous avez besoin et je m’occupe du reste.", "new-chat": "Nouveau chat", - "no-chats": "Aucun chat pour le moment", "today": "Aujourd’hui", "yesterday": "Hier", "last-7-days": "7 derniers jours", @@ -703,18 +700,12 @@ "delete-chat-title": "Voulez-vous vraiment supprimer '{{name}}' ?", "delete-chat-text": "Tous les messages du chat seront perdus", "delete-chat-confirm": "Oui, supprimer", - "action-approval-required": "Approbation de l’action requise", "approve": "Approuver", - "approve-all": "Approuver toutes les actions suivantes", "deny": "Refuser", - "processing": "Traitement en cours...", "approved": "Terminé", - "denied": "Refusé", "error": "Échoué", "thinking": "Réflexion...", - "rename-chat-title": "Renommer ce chat", - "export-chat": "Exporter le chat", - "main-title": "Bonjour ! Je suis votre assistant IA" + "export-chat": "Exporter le chat" }, "alarm": { "alarm": "Alarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Déposez ici le fichier d’identifiants de compte" }, "solution-creator": { - "ai-solution-creator": "Créateur de solution IA", "describe-solution-you-want": "Décrivez une solution que vous souhaitez créer", - "enter-your-prompt": "Saisissez votre invite", "target": "Cible", "install-solution": "Installer", - "solution-overview": "Aperçu de la solution : {{ name }}", - "dashboards-overview": "Aperçu des tableaux de bord : {{ name }}", - "entity-profile": "Profil d’entité", - "entity-profiles": "Profils d’entité", - "name": "Nom", - "iam": "IAM", - "iam-full": "Gestion des identités et des accès", - "table-view": "Tableau", - "schema-view": "Schéma", - "iam-info": "Informations IAM", "operation": { "C": "Créer", "R": "Lire", "U": "Mettre à jour", "D": "Supprimer" }, - "alarm-info": "Informations sur l’alarme", "description": "Description", - "data": "Données", - "entity-info": "Informations sur l’entité", - "calculated-field-info": "Informations sur le champ calculé", - "field-type": "Type de champ", - "scope": "Portée", "delete-alarm-title": "Supprimer cette alarme suggérée ?", "delete-alarm-text": "Cette alarme, suggérée en fonction de votre description, ne sera pas ajoutée à la version de solution proposée.
Vous pourrez toujours modifier ou recréer des alarmes manuellement plus tard. Cette action est irréversible.", - "basic-mode": "Basique", - "advanced-mode": "Avancé", "create-solution": "Créer une solution", "go-dashboard-manager": "Suivant : Conception du tableau de bord", - "success-generate-title": "La solution est prête !", - "success-generate-sub-title": "Vous pouvez l’installer sur votre compte en cliquant sur le bouton ci-dessous", - "success-generate-install-title": "Solution installée !", - "success-generate-install-sub-title": "Pour modifier la solution, veuillez d’abord désinstaller l’instance existante", - "main-title": "Bonjour ! Je suis votre assistant IA", - "sub-title": "Je vous aide à transformer vos besoins en une solution IoT entièrement fonctionnelle.\nDécrivez simplement ce que vous souhaitez accomplir, et je m’occupe du reste.", - "solutions": "Solutions", "new-solution": "Nouvelle solution", "uninstall-solution": "Désinstaller", "uninstall-solution-dialog-title": "Êtes-vous sûr de vouloir désinstaller « {{ name }} » ?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Toutes vos données seront perdues", "delete-solution-confirm": "Oui, supprimer", "copy-solution": "Copier la solution", - "expand-sidebar": "Développer la barre latérale", - "collapse-sidebar": "Réduire la barre latérale", "solution-id": "ID de la solution", "solution-id-required": "L’ID de solution est requis", - "rename-solution-title": "Renommer cette solution", - "generate-again": "Générer à nouveau", "skip-interview": "Passer l’entretien", "update-solution": "Mettre à jour la solution", "finish-edit": "Terminer la modification", @@ -11298,8 +11258,6 @@ "water-metering": "Comptage d’eau", "coffee-machine-monitoring": "Surveillance des machines à café", "fleet-geofencing": "Géorepérage de flotte", - "more-examples": "Plus d’exemples", - "hide": "Masquer", "solution-info": "Informations sur la solution", "solution-info-with-name": "Informations sur la solution : {{ name }}", "status": "Statut", @@ -11312,14 +11270,8 @@ "info": "Infos", "main-dashboard": "Tableau de bord principal", "view-as": "Afficher en tant que {{ name }}", - "generated-by-calculated-field-name": "Généré par le champ calculé « {{ name }} »", "estimate-wait-time": "Le temps d’attente estimé est d’environ {{ time }}", - "analyzing-your-request": "Analyse de votre demande...", "condition": "Condition", - "installing": "Installation de la solution...", - "step-architecture-design": "Conception de l’architecture", - "step-dashboard-design": "Conception du tableau de bord", - "step-solution-installation": "Installation de la solution", "step-reading-device-data": "Lecture des données de l’appareil…", "step-analyzing-telemetry-attributes": "Analyse de la télémétrie et des attributs…", "step-selecting-widgets": "Sélection des widgets pour vos données…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construction des règles d’alarme…", "step-loading-assembling-dashboards": "Assemblage des tableaux de bord…", "step-loading-preparing-states": "Préparation des états…", - "step-loading-initializing-solution": "Initialisation de la solution…", - "ai-credits": "Crédits IA", - "ai-credits-update": "Mettre à jour", - "ai-credits-usage": "Crédits IA : {{ used }} sur {{ max }} utilisés", - "ai-credits-description": "Vous avez utilisé {{ used }} sur {{ max }} crédits IA ce mois-ci. La limite se réinitialise le {{ date }}. Pour augmenter votre allocation de crédits IA, veuillez contacter votre administrateur système." + "step-loading-initializing-solution": "Initialisation de la solution…" }, "markdown": { "edit": "Modifier", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Espace disque faible. Pour éviter une perte de données, libérez ou augmentez l’espace disque.", "disk-critical-text": "Espace disque critique. Pour éviter une perte de données, libérez ou augmentez l’espace disque." }, - "cluster-info": { - "service-id": "ID du service", - "service-type": "Type de service", - "no-data": "Aucune donnée" - }, "transport-messages": { "title": "Messages de transport", "info": "Tous les messages provenant des appareils" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Aucun tableau de bord consulté récemment" }, "configured-features": { - "title": "Fonctionnalités configurées", - "info": "Statut des fonctionnalités nécessitant une configuration", - "white-labeling-feature": "Marque blanche", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Fonctionnalité configurée.\nCliquez pour configurer", "feature-not-configured": "Fonctionnalité non configurée.\nCliquez pour configurer" }, - "version-info": { - "title": "Version", - "contact-us": "Contactez-nous", - "current-version": "Version actuelle", - "current": "Actuelle", - "available-version": "Version disponible", - "available": "Disponible", - "upgrade": "Mettre à niveau", - "version-is-up-to-date": "La version est à jour" - }, - "license-info": { - "title": "Informations sur la licence", - "view-all": "Voir tout", - "license-portal": "Portail des licences", - "devices-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Appareils", - "assets-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Ressources", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Tableaux de bord", - "integrations-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Intégrations", - "community-support": "Support communautaire", - "white-labeling": "Marque blanche", - "unlimited-datapoints-and-messages": "Points de données et messages illimités", - "unlimited-api-calls": "Appels API illimités" - }, "usage-info": { "title": "Utilisation", "entities": "Entités", diff --git a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json index 56de7f7880..25d23470af 100644 --- a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json +++ b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI से कॉन्फ़िगर करें", - "follow-up-prompt-placeholder": "उत्तर दें...", - "sub-title": "मैं आपके डिवाइस, डैशबोर्ड, कैलक्युलेटेड फ़ील्ड, अलार्म नियम और सूचनाओं को सेट अप और प्रबंधित करने में आपकी मदद कर सकता हूँ — बस बताइए आपको क्या चाहिए, बाकी मैं संभाल लूँगा।", "new-chat": "नई चैट", - "no-chats": "अभी तक कोई चैट नहीं", "today": "आज", "yesterday": "कल", "last-7-days": "पिछले 7 दिन", @@ -703,17 +700,11 @@ "delete-chat-title": "क्या आप वाकई '{{name}}' को हटाना चाहते हैं?", "delete-chat-text": "सभी चैट संदेश खो जाएँगे", "delete-chat-confirm": "हाँ, हटाएँ", - "action-approval-required": "कार्रवाई के लिए स्वीकृति आवश्यक", "approve": "स्वीकृत करें", - "approve-all": "आगे की सभी कार्रवाइयों को स्वीकृत करें", "deny": "अस्वीकार करें", - "processing": "प्रोसेस हो रहा है...", "approved": "हो गया", - "denied": "अस्वीकृत", "error": "विफल", "thinking": "सोच रहा हूँ...", - "connection-lost": "AI असिस्टेंट से कनेक्शन टूट गया। फिर से कनेक्ट हो रहा है...", - "reconnect-failed": "AI असिस्टेंट से फिर से कनेक्ट नहीं हो सका। उसका उत्तर देखने के लिए चैट फिर से खोलें।", "ask-the-assistant": "AI असिस्टेंट से पूछें", "send": "भेजें", "new-line": "नई पंक्ति", @@ -740,9 +731,7 @@ "text": "टेक्स्ट", "file": "फ़ाइल" }, - "rename-chat-title": "इस चैट का नाम बदलें", - "export-chat": "चैट एक्सपोर्ट करें", - "main-title": "नमस्ते! मैं आपका AI असिस्टेंट हूँ" + "export-chat": "चैट एक्सपोर्ट करें" }, "alarm": { "alarm": "अलार्म", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "अपनी खाता क्रेडेंशियल्स फ़ाइल ड्रैग और ड्रॉप करें" }, "solution-creator": { - "ai-solution-creator": "AI समाधान निर्माता", "describe-solution-you-want": "वह समाधान बताएँ जो आप बनाना चाहते हैं", - "enter-your-prompt": "अपना प्रॉम्प्ट दर्ज करें", "target": "लक्ष्य", "install-solution": "इंस्टॉल करें", - "solution-overview": "समाधान का अवलोकन: {{ name }}", - "dashboards-overview": "डैशबोर्डों का अवलोकन: {{ name }}", - "entity-profile": "एंटिटी प्रोफ़ाइल", - "entity-profiles": "एंटिटी प्रोफ़ाइल", - "name": "नाम", - "iam": "IAM", - "iam-full": "पहचान और ऐक्सेस प्रबंधन", - "table-view": "टेबल", - "schema-view": "स्कीमा", - "iam-info": "IAM जानकारी", "operation": { "C": "बनाएँ", "R": "पढ़ें", "U": "अपडेट करें", "D": "हटाएँ" }, - "alarm-info": "अलार्म जानकारी", "description": "विवरण", - "data": "डेटा", - "entity-info": "एंटिटी जानकारी", - "calculated-field-info": "कैलक्युलेटेड फ़ील्ड जानकारी", - "field-type": "फ़ील्ड प्रकार", - "scope": "स्कोप", "delete-alarm-title": "क्या आप वाकई इस सुझाए गए अलार्म को हटाना चाहते हैं?", "delete-alarm-text": "आपके विवरण के आधार पर सुझाया गया यह अलार्म प्रस्तावित समाधान बिल्ड में नहीं जोड़ा जाएगा।
आप बाद में कभी भी अलार्मों को मैन्युअल रूप से संपादित कर सकते हैं या फिर से बना सकते हैं। यह क्रिया पूर्ववत नहीं की जा सकती।", - "basic-mode": "बेसिक", - "advanced-mode": "उन्नत", "create-solution": "समाधान बनाएँ", "go-dashboard-manager": "अगला: डैशबोर्ड डिज़ाइन", - "success-generate-title": "समाधान तैयार है!", - "success-generate-sub-title": "नीचे दिए गए बटन पर क्लिक करके आप इसे अपने खाते में इंस्टॉल कर सकते हैं", - "success-generate-install-title": "समाधान इंस्टॉल हो गया!", - "success-generate-install-sub-title": "समाधान को संपादित करने के लिए, कृपया पहले मौजूदा इंस्टेंस को अनइंस्टॉल करें", - "main-title": "नमस्ते! मैं आपका AI असिस्टेंट हूँ", - "sub-title": "मैं आपकी आवश्यकताओं को पूरी तरह से काम करने वाले IoT समाधान में बदलने में आपकी मदद करता हूँ।\nबस बताएँ कि आप क्या हासिल करना चाहते हैं, बाकी मैं संभाल लूँगा।", - "solutions": "समाधान", "new-solution": "नया समाधान", "uninstall-solution": "अनइंस्टॉल करें", "uninstall-solution-dialog-title": "क्या आप वाकई ‘{{ name }}’ को अनइंस्टॉल करना चाहते हैं?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "आपका सारा डेटा खो जाएगा", "delete-solution-confirm": "हाँ, हटाएँ", "copy-solution": "समाधान कॉपी करें", - "expand-sidebar": "साइडबार विस्तृत करें", - "collapse-sidebar": "साइडबार संकुचित करें", "solution-id": "समाधान ID", "solution-id-required": "समाधान ID आवश्यक है", - "rename-solution-title": "इस समाधान का नाम बदलें", - "generate-again": "फिर से जनरेट करें", "skip-interview": "इंटरव्यू छोड़ें", "update-solution": "समाधान अपडेट करें", "finish-edit": "संपादन पूरा करें", @@ -11338,8 +11296,6 @@ "water-metering": "जल मीटरिंग", "coffee-machine-monitoring": "कॉफ़ी मशीन मॉनिटरिंग", "fleet-geofencing": "फ़्लीट जियोफ़ेंसिंग", - "more-examples": "और उदाहरण", - "hide": "छिपाएँ", "solution-info": "समाधान की जानकारी", "solution-info-with-name": "समाधान की जानकारी: {{ name }}", "status": "स्थिति", @@ -11352,14 +11308,8 @@ "info": "जानकारी", "main-dashboard": "मुख्य डैशबोर्ड", "view-as": "{{ name }} के रूप में देखें", - "generated-by-calculated-field-name": "‘{{ name }}’ कैलक्युलेटेड फ़ील्ड द्वारा जनरेट किया गया", "estimate-wait-time": "अनुमानित प्रतीक्षा समय ~{{ time }} है", - "analyzing-your-request": "आपके अनुरोध का विश्लेषण किया जा रहा है...", "condition": "शर्त", - "installing": "समाधान इंस्टॉल किया जा रहा है...", - "step-architecture-design": "आर्किटेक्चर डिज़ाइन", - "step-dashboard-design": "डैशबोर्ड डिज़ाइन", - "step-solution-installation": "समाधान इंस्टॉलेशन", "step-reading-device-data": "डिवाइस डेटा पढ़ा जा रहा है…", "step-analyzing-telemetry-attributes": "टेलीमेट्री और विशेषताओं का विश्लेषण किया जा रहा है…", "step-selecting-widgets": "आपके डेटा के लिए विजेट चुने जा रहे हैं…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "अलार्म नियम बनाए जा रहे हैं…", "step-loading-assembling-dashboards": "डैशबोर्ड तैयार किए जा रहे हैं…", "step-loading-preparing-states": "स्टेट तैयार किए जा रहे हैं…", - "step-loading-initializing-solution": "समाधान आरंभ किया जा रहा है…", - "ai-credits": "AI क्रेडिट", - "ai-credits-update": "प्लान अपग्रेड करें", - "ai-credits-usage": "AI क्रेडिट: {{ max }} में से {{ used }} उपयोग किए गए", - "ai-credits-description": "आपने इस महीने अपने {{ max }} AI क्रेडिट में से {{ used }} का उपयोग किया है। सीमा {{ date }} को रीसेट होगी। अपनी AI क्रेडिट सीमा बढ़ाने के लिए, कृपया अपने सिस्टम एडमिनिस्ट्रेटर से संपर्क करें।" + "step-loading-initializing-solution": "समाधान आरंभ किया जा रहा है…" }, "markdown": { "edit": "संपादित करें", @@ -13821,11 +13767,6 @@ "disk-warning-text": "डिस्क स्पेस कम हो रहा है। डेटा हानि से बचने के लिए डिस्क स्पेस खाली करें या बढ़ाएँ।", "disk-critical-text": "डिस्क स्पेस अत्यधिक कम है। डेटा हानि से बचने के लिए डिस्क स्पेस खाली करें या बढ़ाएँ।" }, - "cluster-info": { - "service-id": "सर्विस ID", - "service-type": "सर्विस प्रकार", - "no-data": "कोई डेटा नहीं" - }, "transport-messages": { "title": "ट्रांसपोर्ट संदेश", "info": "डिवाइसों से आए सभी संदेश" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "अभी तक कोई हाल में देखा गया डैशबोर्ड नहीं" }, "configured-features": { - "title": "कॉन्फ़िगर किए गए फ़ीचर", - "info": "ऐसे फ़ीचरों की स्थिति जिन्हें कॉन्फ़िगरेशन की आवश्यकता है", - "white-labeling-feature": "व्हाइट लेबलिंग", - "email-feature": "ईमेल", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "फ़ीचर कॉन्फ़िगर है।\nसेटअप करने के लिए क्लिक करें", "feature-not-configured": "फ़ीचर कॉन्फ़िगर नहीं है।\nसेटअप करने के लिए क्लिक करें" }, - "version-info": { - "title": "संस्करण", - "contact-us": "हमसे संपर्क करें", - "current-version": "वर्तमान संस्करण", - "current": "वर्तमान", - "available-version": "उपलब्ध संस्करण", - "available": "उपलब्ध", - "upgrade": "अपग्रेड करें", - "version-is-up-to-date": "संस्करण नवीनतम है" - }, - "license-info": { - "title": "लाइसेंस जानकारी", - "view-all": "सभी देखें", - "license-portal": "लाइसेंस पोर्टल", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } डिवाइस", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } एसेट", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } डैशबोर्ड", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } इंटीग्रेशन", - "community-support": "कम्युनिटी सपोर्ट", - "white-labeling": "व्हाइट लेबलिंग", - "unlimited-datapoints-and-messages": "असीमित डेटापॉइंट और संदेश", - "unlimited-api-calls": "असीमित API कॉल" - }, "usage-info": { "title": "उपयोग", "entities": "एंटिटी", diff --git a/ui-ngx/src/assets/locale/locale.constant-it_IT.json b/ui-ngx/src/assets/locale/locale.constant-it_IT.json index 52675dc7eb..40588f4ce1 100644 --- a/ui-ngx/src/assets/locale/locale.constant-it_IT.json +++ b/ui-ngx/src/assets/locale/locale.constant-it_IT.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configura con l'IA", - "follow-up-prompt-placeholder": "Rispondi...", - "sub-title": "Posso aiutarti a configurare e gestire i tuoi dispositivi, le dashboard, i campi calcolati, le regole di allarme e le notifiche: descrivi semplicemente ciò di cui hai bisogno e penserò io al resto.", "new-chat": "Nuova chat", - "no-chats": "Nessuna chat ancora", "today": "Oggi", "yesterday": "Ieri", "last-7-days": "Ultimi 7 giorni", @@ -703,18 +700,12 @@ "delete-chat-title": "Sei sicuro di voler eliminare '{{name}}'?", "delete-chat-text": "Tutti i messaggi della chat andranno persi", "delete-chat-confirm": "Sì, elimina", - "action-approval-required": "Approvazione dell'azione richiesta", "approve": "Approva", - "approve-all": "Approva tutte le azioni successive", "deny": "Nega", - "processing": "Elaborazione in corso...", "approved": "Fatto", - "denied": "Negato", "error": "Non riuscito", "thinking": "Sto pensando...", - "rename-chat-title": "Rinomina questa chat", - "export-chat": "Esporta chat", - "main-title": "Ciao! Sono il tuo assistente IA" + "export-chat": "Esporta chat" }, "alarm": { "alarm": "Allarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Trascina e rilascia il file delle credenziali dell'account" }, "solution-creator": { - "ai-solution-creator": "Creatore di soluzioni IA", "describe-solution-you-want": "Descrivi la soluzione che vuoi creare", - "enter-your-prompt": "Inserisci il tuo prompt", "target": "Destinazione", "install-solution": "Installa", - "solution-overview": "Panoramica della soluzione: {{ name }}", - "dashboards-overview": "Panoramica delle dashboard: {{ name }}", - "entity-profile": "Profilo entità", - "entity-profiles": "Profili entità", - "name": "Nome", - "iam": "IAM", - "iam-full": "Gestione delle identità e degli accessi", - "table-view": "Tabella", - "schema-view": "Schema", - "iam-info": "Info IAM", "operation": { "C": "Crea", "R": "Leggi", "U": "Modifica", "D": "Elimina" }, - "alarm-info": "Informazioni sull'allarme", "description": "Descrizione", - "data": "Dati", - "entity-info": "Informazioni sull'entità", - "calculated-field-info": "Informazioni sul campo calcolato", - "field-type": "Tipo di campo", - "scope": "Ambito", "delete-alarm-title": "Eliminare questo allarme suggerito?", "delete-alarm-text": "Questo allarme, suggerito in base alla tua descrizione, non verrà aggiunto alla soluzione proposta.
Puoi sempre modificare o ricreare gli allarmi manualmente in seguito. Questa azione non può essere annullata.", - "basic-mode": "Base", - "advanced-mode": "Avanzato", "create-solution": "Crea soluzione", "go-dashboard-manager": "Avanti: progettazione della dashboard", - "success-generate-title": "La soluzione è pronta!", - "success-generate-sub-title": "Puoi installarla sul tuo account facendo clic sul pulsante qui sotto", - "success-generate-install-title": "Soluzione installata!", - "success-generate-install-sub-title": "Per modificare la soluzione, disinstalla prima l'istanza esistente", - "main-title": "Ciao! Sono il tuo assistente IA", - "sub-title": "Ti aiuto a trasformare i tuoi requisiti in una soluzione IoT completamente funzionante.\nDescrivi semplicemente cosa vuoi ottenere e al resto penso io.", - "solutions": "Soluzioni", "new-solution": "Nuova soluzione", "uninstall-solution": "Disinstalla", "uninstall-solution-dialog-title": "Sei sicuro di voler disinstallare ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Tutti i tuoi dati andranno persi", "delete-solution-confirm": "Sì, elimina", "copy-solution": "Copia soluzione", - "expand-sidebar": "Espandi barra laterale", - "collapse-sidebar": "Comprimi barra laterale", "solution-id": "ID soluzione", "solution-id-required": "L'ID soluzione è obbligatorio", - "rename-solution-title": "Rinomina questa soluzione", - "generate-again": "Genera di nuovo", "skip-interview": "Salta intervista", "update-solution": "Aggiorna soluzione", "finish-edit": "Termina modifica", @@ -11298,8 +11258,6 @@ "water-metering": "Misurazione dei consumi idrici", "coffee-machine-monitoring": "Monitoraggio macchine del caffè", "fleet-geofencing": "Geofencing della flotta", - "more-examples": "Altri esempi", - "hide": "Nascondi", "solution-info": "Informazioni sulla soluzione", "solution-info-with-name": "Informazioni sulla soluzione: {{ name }}", "status": "Stato", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Dashboard principale", "view-as": "Visualizza come {{ name }}", - "generated-by-calculated-field-name": "Generato dal campo calcolato ‘{{ name }}’", "estimate-wait-time": "Il tempo di attesa stimato è di ~{{ time }}", - "analyzing-your-request": "Analisi della tua richiesta in corso...", "condition": "Condizione", - "installing": "Installazione della soluzione in corso...", - "step-architecture-design": "Progettazione dell'architettura", - "step-dashboard-design": "Progettazione della dashboard", - "step-solution-installation": "Installazione della soluzione", "step-reading-device-data": "Lettura dei dati del dispositivo…", "step-analyzing-telemetry-attributes": "Analisi di telemetria e attributi…", "step-selecting-widgets": "Selezione dei widget per i tuoi dati…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Creazione delle regole di allarme…", "step-loading-assembling-dashboards": "Assemblaggio delle dashboard…", "step-loading-preparing-states": "Preparazione degli stati…", - "step-loading-initializing-solution": "Inizializzazione della soluzione…", - "ai-credits": "Crediti IA", - "ai-credits-update": "Cambia piano", - "ai-credits-usage": "Crediti IA: {{ used }} di {{ max }} utilizzati", - "ai-credits-description": "Hai utilizzato {{ used }} dei tuoi {{ max }} crediti IA questo mese. Il limite si azzera il {{ date }}. Per aumentare la tua disponibilità di crediti IA, contatta l'amministratore di sistema." + "step-loading-initializing-solution": "Inizializzazione della soluzione…" }, "markdown": { "edit": "Modifica", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Spazio su disco in esaurimento. Per evitare la perdita di dati, libera o amplia lo spazio su disco.", "disk-critical-text": "Spazio su disco criticamente basso. Per evitare la perdita di dati, libera o amplia lo spazio su disco." }, - "cluster-info": { - "service-id": "ID servizio", - "service-type": "Tipo di servizio", - "no-data": "Nessun dato" - }, "transport-messages": { "title": "Messaggi di trasporto", "info": "Tutti i messaggi provenienti dai dispositivi" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Nessuna dashboard visualizzata di recente" }, "configured-features": { - "title": "Funzionalità configurate", - "info": "Stato delle funzionalità che richiedono configurazione", - "white-labeling-feature": "Personalizzazione del marchio", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funzionalità configurata.\nClicca per configurare", "feature-not-configured": "Funzionalità non configurata.\nClicca per configurare" }, - "version-info": { - "title": "Versione", - "contact-us": "Contattaci", - "current-version": "Versione corrente", - "current": "Corrente", - "available-version": "Versione disponibile", - "available": "Disponibile", - "upgrade": "Effettua l'upgrade", - "version-is-up-to-date": "La versione è aggiornata" - }, - "license-info": { - "title": "Informazioni sulla licenza", - "view-all": "Vedi tutto", - "license-portal": "Portale licenze", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivi", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Asset", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboard", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrazioni", - "community-support": "Supporto della community", - "white-labeling": "Personalizzazione del marchio", - "unlimited-datapoints-and-messages": "Punti dati e messaggi illimitati", - "unlimited-api-calls": "Chiamate API illimitate" - }, "usage-info": { "title": "Utilizzo", "entities": "Entità", diff --git a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json index 2abd46f029..69eff0732e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json +++ b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI で構成", - "follow-up-prompt-placeholder": "返信...", - "sub-title": "デバイス、ダッシュボード、計算フィールド、アラームルール、通知の設定と管理をお手伝いします。必要なことを説明していただければ、あとはお任せください。", "new-chat": "新しいチャット", - "no-chats": "チャットはまだありません", "today": "今日", "yesterday": "昨日", "last-7-days": "過去 7 日", @@ -703,18 +700,12 @@ "delete-chat-title": "'{{name}}' を削除してもよろしいですか?", "delete-chat-text": "すべてのチャットメッセージが失われます", "delete-chat-confirm": "はい、削除します", - "action-approval-required": "操作の承認が必要です", "approve": "承認", - "approve-all": "以降のすべてのアクションを承認", "deny": "拒否", - "processing": "処理中...", "approved": "完了", - "denied": "拒否済み", "error": "失敗", "thinking": "考え中...", - "rename-chat-title": "このチャットの名前を変更", - "export-chat": "チャットをエクスポート", - "main-title": "こんにちは!AI アシスタントです" + "export-chat": "チャットをエクスポート" }, "alarm": { "alarm": "アラーム", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "アカウント認証情報ファイルをドラッグ&ドロップ" }, "solution-creator": { - "ai-solution-creator": "AIソリューション作成", "describe-solution-you-want": "作成したいソリューションを説明してください", - "enter-your-prompt": "プロンプトを入力", "target": "ターゲット", "install-solution": "インストール", - "solution-overview": "ソリューションの概要: {{ name }}", - "dashboards-overview": "ダッシュボードの概要: {{ name }}", - "entity-profile": "エンティティプロファイル", - "entity-profiles": "エンティティプロファイル", - "name": "名前", - "iam": "IAM", - "iam-full": "IDおよびアクセス管理", - "table-view": "テーブル", - "schema-view": "スキーマ", - "iam-info": "IAM情報", "operation": { "C": "作成", "R": "読み取り", "U": "更新", "D": "削除" }, - "alarm-info": "アラーム情報", "description": "説明", - "data": "データ", - "entity-info": "エンティティ情報", - "calculated-field-info": "計算フィールド情報", - "field-type": "フィールドタイプ", - "scope": "スコープ", "delete-alarm-title": "この提案されたアラームを削除しますか?", "delete-alarm-text": "説明に基づいて提案されたこのアラームは、提案されたソリューションのビルドに追加されません。
アラームは後からいつでも手動で編集または再作成できます。この操作は元に戻せません。", - "basic-mode": "基本", - "advanced-mode": "詳細", "create-solution": "ソリューションを作成", "go-dashboard-manager": "次へ: ダッシュボード設計", - "success-generate-title": "ソリューションの準備ができました!", - "success-generate-sub-title": "下のボタンをクリックすると、お使いのアカウントにインストールできます。", - "success-generate-install-title": "ソリューションがインストールされました!", - "success-generate-install-sub-title": "ソリューションを編集するには、まず既存のインスタンスをアンインストールしてください。", - "main-title": "こんにちは!AIアシスタントです", - "sub-title": "要件を完全に機能するIoTソリューションに変換するお手伝いをします。\n実現したいことを説明していただければ、残りは私が対応します。", - "solutions": "ソリューション", "new-solution": "新しいソリューション", "uninstall-solution": "アンインストール", "uninstall-solution-dialog-title": "‘{{ name }}’をアンインストールしてもよろしいですか?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "すべてのデータが失われます", "delete-solution-confirm": "はい、削除します", "copy-solution": "ソリューションをコピー", - "expand-sidebar": "サイドバーを展開", - "collapse-sidebar": "サイドバーを折りたたむ", "solution-id": "ソリューションID", "solution-id-required": "ソリューションIDは必須です。", - "rename-solution-title": "このソリューションの名前を変更", - "generate-again": "再生成", "skip-interview": "インタビューをスキップ", "update-solution": "ソリューションを更新", "finish-edit": "編集を終了", @@ -11298,8 +11258,6 @@ "water-metering": "水道検針", "coffee-machine-monitoring": "コーヒーマシンのモニタリング", "fleet-geofencing": "車両ジオフェンシング", - "more-examples": "その他の例", - "hide": "非表示", "solution-info": "ソリューション情報", "solution-info-with-name": "ソリューション情報: {{ name }}", "status": "ステータス", @@ -11312,14 +11270,8 @@ "info": "情報", "main-dashboard": "メインダッシュボード", "view-as": "{{ name }}として表示", - "generated-by-calculated-field-name": "計算フィールド‘{{ name }}’によって生成", "estimate-wait-time": "推定待ち時間は約{{ time }}です。", - "analyzing-your-request": "リクエストを分析しています...", "condition": "条件", - "installing": "ソリューションをインストールしています...", - "step-architecture-design": "アーキテクチャ設計", - "step-dashboard-design": "ダッシュボード設計", - "step-solution-installation": "ソリューションのインストール", "step-reading-device-data": "デバイスデータを読み取っています…", "step-analyzing-telemetry-attributes": "テレメトリと属性を分析しています…", "step-selecting-widgets": "データに適したウィジェットを選択しています…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "アラームルールを構築しています…", "step-loading-assembling-dashboards": "ダッシュボードを構成しています…", "step-loading-preparing-states": "状態を準備しています…", - "step-loading-initializing-solution": "ソリューションを初期化しています…", - "ai-credits": "AIクレジット", - "ai-credits-update": "プランを変更", - "ai-credits-usage": "AIクレジット: {{ used }}/{{ max }}使用済み", - "ai-credits-description": "今月はAIクレジット{{ max }}のうち{{ used }}を使用しました。上限は{{ date }}にリセットされます。AIクレジットの上限を増やすには、システム管理者にお問い合わせください。" + "step-loading-initializing-solution": "ソリューションを初期化しています…" }, "markdown": { "edit": "編集", @@ -13781,11 +13729,6 @@ "disk-warning-text": "ディスクの空き容量が少なくなっています。データ損失を避けるため、ディスクの空き容量を確保するか、ディスクの容量を増加させてください。", "disk-critical-text": "ディスクの空き容量が非常に少ない状態です。データ損失を避けるため、ディスクの空き容量を確保するか、ディスクの容量を増加させてください。" }, - "cluster-info": { - "service-id": "サービスID", - "service-type": "サービスタイプ", - "no-data": "データなし" - }, "transport-messages": { "title": "トランスポートメッセージ", "info": "デバイスから送信されたすべてのメッセージ" @@ -13824,41 +13767,9 @@ "no-last-viewed-dashboards": "最後に表示したダッシュボードはまだありません" }, "configured-features": { - "title": "設定された機能", - "info": "設定が必要な機能の状態", - "white-labeling-feature": "ホワイトラベリング", - "email-feature": "メール", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "機能は設定されています。\n設定するにはクリック", "feature-not-configured": "機能は設定されていません。\n設定するにはクリック" }, - "version-info": { - "title": "バージョン", - "contact-us": "お問い合わせ", - "current-version": "現在のバージョン", - "current": "現行", - "available-version": "利用可能なバージョン", - "available": "利用可能", - "upgrade": "アップグレード", - "version-is-up-to-date": "バージョンは最新です" - }, - "license-info": { - "title": "ライセンス情報", - "view-all": "すべて表示", - "license-portal": "ライセンスポータル", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } デバイス", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } アセット", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } ダッシュボード", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } 統合", - "community-support": "コミュニティサポート", - "white-labeling": "ホワイトラベリング", - "unlimited-datapoints-and-messages": "無制限のデータポイントとメッセージ", - "unlimited-api-calls": "無制限のAPI呼び出し" - }, "usage-info": { "title": "使用状況", "entities": "エンティティ", diff --git a/ui-ngx/src/assets/locale/locale.constant-ka_GE.json b/ui-ngx/src/assets/locale/locale.constant-ka_GE.json index f5f661cd8e..cc6050177d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ka_GE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ka_GE.json @@ -132,10 +132,7 @@ }, "ai-assistant": { "configure-with-ai": "კონფიგურაცია AI-ის დახმარებით", - "follow-up-prompt-placeholder": "პასუხი...", - "sub-title": "შემიძლია დაგეხმაროთ თქვენი მოწყობილობების, დაფების, გამოთვლილი ველების, განგაშის წესებისა და შეტყობინებების დაყენებასა და მართვაში — უბრალოდ აღწერეთ, რა გჭირდებათ, დანარჩენს მე მოვაგვარებ.", "new-chat": "ახალი ჩატი", - "no-chats": "ჩატები ჯერ არ არის", "today": "დღეს", "yesterday": "გუშინ", "last-7-days": "ბოლო 7 დღე", @@ -143,16 +140,11 @@ "delete-chat-title": "ნამდვილად გსურთ '{{name}}'-ის წაშლა?", "delete-chat-text": "ჩატის ყველა შეტყობინება დაიკარგება", "delete-chat-confirm": "კი, წაშლა", - "action-approval-required": "საჭიროა მოქმედების დამტკიცება", "approve": "დამტკიცება", "deny": "უარყოფა", - "processing": "მიმდინარეობს დამუშავება...", "approved": "შესრულებულია", - "denied": "უარყოფილია", "error": "ვერ მოხერხდა", - "thinking": "ვფიქრობ...", - "rename-chat-title": "ამ ჩატის სახელის შეცვლა", - "main-title": "გამარჯობა! მე ვარ თქვენი AI ასისტენტი" + "thinking": "ვფიქრობ..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "განგაშის წესების შეთავაზება", diff --git a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json index eb466cf98a..aa0ebe127b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json +++ b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI로 구성", - "follow-up-prompt-placeholder": "답장...", - "sub-title": "장치, 대시보드, 계산 필드, 알람 규칙, 알림을 설정하고 관리하는 것을 도와드릴 수 있습니다. 필요한 것을 설명해 주시면 나머지는 제가 처리하겠습니다.", "new-chat": "새 채팅", - "no-chats": "아직 채팅이 없습니다", "today": "오늘", "yesterday": "어제", "last-7-days": "지난 7일", @@ -703,17 +700,11 @@ "delete-chat-title": "'{{name}}'을(를) 삭제하시겠습니까?", "delete-chat-text": "모든 채팅 메시지가 손실됩니다", "delete-chat-confirm": "예, 삭제", - "action-approval-required": "액션 승인이 필요합니다", "approve": "승인", - "approve-all": "이후 모든 액션 승인", "deny": "거부", - "processing": "처리 중...", "approved": "완료", - "denied": "거부됨", "error": "실패", "thinking": "생각 중...", - "connection-lost": "AI 어시스턴트와의 연결이 끊어졌습니다. 다시 연결하는 중...", - "reconnect-failed": "AI 어시스턴트에 다시 연결할 수 없습니다. 응답을 보려면 채팅을 다시 여세요.", "ask-the-assistant": "AI 어시스턴트에게 질문", "send": "보내기", "new-line": "줄 바꿈", @@ -740,9 +731,7 @@ "text": "텍스트", "file": "파일" }, - "rename-chat-title": "이 채팅 이름 바꾸기", - "export-chat": "채팅 내보내기", - "main-title": "안녕하세요! AI 어시스턴트입니다" + "export-chat": "채팅 내보내기" }, "alarm-rule": { "ai-assistant-initial-prompt-placeholder": "설정하려는 내용을 설명해 주세요...", @@ -11347,47 +11336,20 @@ "select-recaptcha-enterprise-service-account-file": "계정 자격 증명 파일을 끌어서 놓으세요" }, "solution-creator": { - "ai-solution-creator": "AI 솔루션 생성기", "describe-solution-you-want": "만들려는 솔루션을 설명하세요", - "enter-your-prompt": "프롬프트를 입력하세요", "target": "대상", "install-solution": "설치", - "solution-overview": "솔루션 개요: {{ name }}", - "dashboards-overview": "대시보드 개요: {{ name }}", - "entity-profile": "엔티티 프로필", - "entity-profiles": "엔티티 프로필", - "name": "이름", - "iam": "IAM", - "iam-full": "ID 및 액세스 관리", - "table-view": "테이블", - "schema-view": "스키마", - "iam-info": "IAM 정보", "operation": { "C": "생성", "R": "읽기", "U": "업데이트", "D": "삭제" }, - "alarm-info": "알람 정보", "description": "설명", - "data": "데이터", - "entity-info": "엔티티 정보", - "calculated-field-info": "계산 필드 정보", - "field-type": "필드 유형", - "scope": "범위", "delete-alarm-title": "제안된 이 알람을 삭제하시겠습니까?", "delete-alarm-text": "입력하신 설명을 바탕으로 제안된 이 알람은 제안된 솔루션 빌드에 추가되지 않습니다.
나중에 언제든지 알람을 수동으로 편집하거나 다시 생성할 수 있습니다. 이 작업은 실행 취소할 수 없습니다.", - "basic-mode": "기본", - "advanced-mode": "고급", "create-solution": "솔루션 생성", "go-dashboard-manager": "다음: 대시보드 디자인", - "success-generate-title": "솔루션이 준비되었습니다!", - "success-generate-sub-title": "아래 버튼을 클릭하여 계정에 설치할 수 있습니다", - "success-generate-install-title": "솔루션이 설치되었습니다!", - "success-generate-install-sub-title": "솔루션을 편집하려면 먼저 기존 인스턴스를 제거하세요", - "main-title": "안녕하세요! AI 어시스턴트입니다", - "sub-title": "요구 사항을 완전히 작동하는 IoT 솔루션으로 구현하도록 도와드립니다.\n원하는 목표를 설명해 주시면 나머지는 제가 처리하겠습니다.", - "solutions": "솔루션", "new-solution": "새 솔루션", "uninstall-solution": "제거", "uninstall-solution-dialog-title": "‘{{ name }}’을(를) 제거하시겠습니까?", @@ -11397,12 +11359,8 @@ "delete-solution-text": "모든 데이터가 손실됩니다", "delete-solution-confirm": "예, 삭제", "copy-solution": "솔루션 복사", - "expand-sidebar": "사이드바 확장", - "collapse-sidebar": "사이드바 축소", "solution-id": "솔루션 ID", "solution-id-required": "솔루션 ID는 필수 항목입니다.", - "rename-solution-title": "이 솔루션 이름 변경", - "generate-again": "다시 생성", "skip-interview": "인터뷰 생략", "update-solution": "솔루션 업데이트", "finish-edit": "편집 완료", @@ -11412,8 +11370,6 @@ "water-metering": "수도 계량", "coffee-machine-monitoring": "커피 머신 모니터링", "fleet-geofencing": "차량 지오펜싱", - "more-examples": "더 많은 예시", - "hide": "숨기기", "solution-info": "솔루션 정보", "solution-info-with-name": "솔루션 정보: {{ name }}", "status": "상태", @@ -11426,14 +11382,8 @@ "info": "정보", "main-dashboard": "메인 대시보드", "view-as": "{{ name }}(으)로 보기", - "generated-by-calculated-field-name": "‘{{ name }}’ 계산 필드에서 생성됨", "estimate-wait-time": "예상 대기 시간은 약 {{ time }}입니다", - "analyzing-your-request": "요청을 분석하는 중...", "condition": "조건", - "installing": "솔루션 설치 중...", - "step-architecture-design": "아키텍처 설계", - "step-dashboard-design": "대시보드 디자인", - "step-solution-installation": "솔루션 설치", "step-reading-device-data": "장치 데이터 읽는 중…", "step-analyzing-telemetry-attributes": "텔레메트리 및 속성 분석 중…", "step-selecting-widgets": "데이터에 맞는 위젯 선택 중…", @@ -11465,11 +11415,7 @@ "step-loading-building-alarm-rules": "알람 규칙 생성 중…", "step-loading-assembling-dashboards": "대시보드 조립 중…", "step-loading-preparing-states": "상태 준비 중…", - "step-loading-initializing-solution": "솔루션 초기화 중…", - "ai-credits": "AI 크레딧", - "ai-credits-update": "플랜 변경", - "ai-credits-usage": "AI 크레딧: {{ max }}개 중 {{ used }}개 사용", - "ai-credits-description": "이번 달 AI 크레딧 {{ max }}개 중 {{ used }}개를 사용했습니다. 한도는 {{ date }}에 재설정됩니다. AI 크레딧 한도를 늘리려면 시스템 관리자에게 문의하세요." + "step-loading-initializing-solution": "솔루션 초기화 중…" }, "widgets": { "mobile-app-qr-code": { @@ -13813,11 +13759,6 @@ "disk-warning-text": "디스크 공간이 부족합니다. 데이터 손실을 방지하려면 디스크 공간을 확보하거나 늘리세요.", "disk-critical-text": "디스크 공간이 매우 부족합니다. 데이터 손실을 방지하려면 디스크 공간을 확보하거나 늘리세요." }, - "cluster-info": { - "service-id": "서비스 ID", - "service-type": "서비스 유형", - "no-data": "데이터 없음" - }, "transport-messages": { "title": "전송 메시지", "info": "장치에서 온 모든 메시지" @@ -13856,41 +13797,9 @@ "no-last-viewed-dashboards": "아직 최근 본 대시보드 없음" }, "configured-features": { - "title": "구성된 기능", - "info": "구성이 필요한 기능 상태", - "white-labeling-feature": "화이트 라벨링", - "email-feature": "이메일", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2단계 인증", "feature-configured": "기능이 구성되었습니다.\n클릭하여 설정", "feature-not-configured": "기능이 구성되지 않았습니다.\n클릭하여 설정" }, - "version-info": { - "title": "버전", - "contact-us": "문의하기", - "current-version": "현재 버전", - "current": "현재", - "available-version": "사용 가능한 버전", - "available": "사용 가능", - "upgrade": "업그레이드", - "version-is-up-to-date": "버전이 최신 상태입니다" - }, - "license-info": { - "title": "라이선스 정보", - "view-all": "모두 보기", - "license-portal": "라이선스 포털", - "devices-info": "장치 {count} / { max, plural, =0 {∞} other {#} }", - "assets-info": "자산 {count} / { max, plural, =0 {∞} other {#} }", - "edges-info": "Edge {count} / { max, plural, =0 {∞} other {#} }", - "dashboards-info": "대시보드 {count} / { max, plural, =0 {∞} other {#} }", - "integrations-info": "통합 {count} / { max, plural, =0 {∞} other {#} }", - "community-support": "커뮤니티 지원", - "white-labeling": "화이트 라벨링", - "unlimited-datapoints-and-messages": "무제한 데이터 포인트 및 메시지", - "unlimited-api-calls": "무제한 API 호출" - }, "usage-info": { "title": "사용량", "entities": "엔티티", diff --git a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json index 9268a71e6a..179bfb4476 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json +++ b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigūruoti naudojant DI", - "follow-up-prompt-placeholder": "Atsakykite...", - "sub-title": "Galiu padėti jums nustatyti ir valdyti jūsų įrenginius, skydelius, apskaičiuotus laukus, įspėjimų taisykles ir pranešimus — tiesiog apibūdinkite, ko jums reikia, o likusiais pasirūpinsiu aš.", "new-chat": "Naujas pokalbis", - "no-chats": "Pokalbių dar nėra", "today": "Šiandien", "yesterday": "Vakar", "last-7-days": "Paskutinės 7 dienos", @@ -703,17 +700,11 @@ "delete-chat-title": "Ar tikrai norite ištrinti „{{name}}“?", "delete-chat-text": "Visi pokalbio pranešimai bus prarasti", "delete-chat-confirm": "Taip, ištrinti", - "action-approval-required": "Reikalingas veiksmo patvirtinimas", "approve": "Patvirtinti", - "approve-all": "Patvirtinti visus tolesnius veiksmus", "deny": "Atmesti", - "processing": "Apdorojama...", "approved": "Atlikta", - "denied": "Atmesta", "error": "Nepavyko", "thinking": "Galvoju...", - "connection-lost": "Ryšys su DI asistentu nutrūko. Jungiamasi iš naujo...", - "reconnect-failed": "Nepavyko iš naujo prisijungti prie DI asistento. Atidarykite pokalbį iš naujo, kad pamatytumėte jo atsakymą.", "ask-the-assistant": "Paklausti DI asistento", "send": "Siųsti", "new-line": "Nauja eilutė", @@ -740,9 +731,7 @@ "text": "Tekstas", "file": "Failas" }, - "rename-chat-title": "Pervadinti šį pokalbį", - "export-chat": "Eksportuoti pokalbį", - "main-title": "Sveiki! Aš esu jūsų DI asistentas" + "export-chat": "Eksportuoti pokalbį" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Siūlyti įspėjimų taisykles", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "Nuvilkite savo paskyros prisijungimo duomenų failą" }, "solution-creator": { - "ai-solution-creator": "DI sprendimų kūrėjas", "describe-solution-you-want": "Aprašykite sprendimą, kurį norite sukurti", - "enter-your-prompt": "Įveskite užklausą", "target": "Tikslas", "install-solution": "Įdiegti", - "solution-overview": "Sprendimo apžvalga: {{ name }}", - "dashboards-overview": "Skydelių apžvalga: {{ name }}", - "entity-profile": "Subjekto profilis", - "entity-profiles": "Subjektų profiliai", - "name": "Pavadinimas", - "iam": "IAM", - "iam-full": "Tapatybių ir prieigos valdymas", - "table-view": "Lentelė", - "schema-view": "Schema", - "iam-info": "IAM informacija", "operation": { "C": "Sukurti", "R": "Skaityti", "U": "Keisti", "D": "Ištrinti" }, - "alarm-info": "Įspėjimo informacija", "description": "Aprašymas", - "data": "Duomenys", - "entity-info": "Subjekto informacija", - "calculated-field-info": "Apskaičiuoto lauko informacija", - "field-type": "Lauko tipas", - "scope": "Taikymo sritis", "delete-alarm-title": "Ištrinti šį pasiūlytą įspėjimą?", "delete-alarm-text": "Šis pagal jūsų aprašymą pasiūlytas įspėjimas nebus įtrauktas į siūlomo sprendimo rinkinį.
Vėliau visada galėsite įspėjimus redaguoti arba sukurti iš naujo rankiniu būdu. Šio veiksmo anuliuoti negalima.", - "basic-mode": "Paprastas režimas", - "advanced-mode": "Išplėstinis režimas", "create-solution": "Sukurti sprendimą", "go-dashboard-manager": "Toliau: skydelio dizainas", - "success-generate-title": "Sprendimas paruoštas!", - "success-generate-sub-title": "Galite jį įdiegti savo paskyroje spustelėję toliau esantį mygtuką", - "success-generate-install-title": "Sprendimas įdiegtas!", - "success-generate-install-sub-title": "Norėdami redaguoti sprendimą, pirmiausia išdiekite esamą egzempliorių", - "main-title": "Sveiki! Aš esu jūsų DI asistentas", - "sub-title": "Padedu jūsų reikalavimus paversti visiškai veikiančiu IoT sprendimu.\nTiesiog aprašykite, ko norite pasiekti, o visa kita padarysiu aš.", - "solutions": "Sprendimai", "new-solution": "Naujas sprendimas", "uninstall-solution": "Išdiegti", "uninstall-solution-dialog-title": "Ar tikrai norite išdiegti „{{ name }}“?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "Visi jūsų duomenys bus prarasti", "delete-solution-confirm": "Taip, ištrinti", "copy-solution": "Kopijuoti sprendimą", - "expand-sidebar": "Išskleisti šoninę juostą", - "collapse-sidebar": "Suskleisti šoninę juostą", "solution-id": "Sprendimo ID", "solution-id-required": "Sprendimo ID yra privalomas", - "rename-solution-title": "Pervadinti šį sprendimą", - "generate-again": "Generuoti dar kartą", "skip-interview": "Praleisti interviu", "update-solution": "Atnaujinti sprendimą", "finish-edit": "Baigti redaguoti", @@ -11338,8 +11296,6 @@ "water-metering": "Vandens apskaita", "coffee-machine-monitoring": "Kavos aparatų stebėsena", "fleet-geofencing": "Transporto parko geozonos", - "more-examples": "Daugiau pavyzdžių", - "hide": "Slėpti", "solution-info": "Sprendimo informacija", "solution-info-with-name": "Sprendimo informacija: {{ name }}", "status": "Būsena", @@ -11352,14 +11308,8 @@ "info": "Informacija", "main-dashboard": "Pagrindinis skydelis", "view-as": "Peržiūrėti kaip {{ name }}", - "generated-by-calculated-field-name": "Sugeneruota apskaičiuoto lauko „{{ name }}“", "estimate-wait-time": "Numatomas laukimo laikas – ~{{ time }}", - "analyzing-your-request": "Analizuojama jūsų užklausa...", "condition": "Sąlyga", - "installing": "Diegiamas sprendimas...", - "step-architecture-design": "Architektūros projektavimas", - "step-dashboard-design": "Skydelio projektavimas", - "step-solution-installation": "Sprendimo diegimas", "step-reading-device-data": "Skaitomi įrenginio duomenys…", "step-analyzing-telemetry-attributes": "Analizuojama telemetrija ir atributai…", "step-selecting-widgets": "Parenkami valdikliai jūsų duomenims…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "Kuriamos įspėjimų taisyklės…", "step-loading-assembling-dashboards": "Komponuojami skydeliai…", "step-loading-preparing-states": "Ruošiamos būsenos…", - "step-loading-initializing-solution": "Inicijuojamas sprendimas…", - "ai-credits": "DI kreditai", - "ai-credits-update": "Keisti planą", - "ai-credits-usage": "DI kreditai: panaudota {{ used }} iš {{ max }}", - "ai-credits-description": "Šį mėnesį panaudojote {{ used }} iš savo {{ max }} DI kreditų. Limitas atsinaujins {{ date }}. Norėdami padidinti DI kreditų limitą, susisiekite su sistemos administratoriumi." + "step-loading-initializing-solution": "Inicijuojamas sprendimas…" }, "markdown": { "edit": "Redaguoti", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Baigiasi vieta diske. Kad neprarastumėte duomenų, atlaisvinkite arba išplėskite disko vietą.", "disk-critical-text": "Kritiškai mažai vietos diske. Kad neprarastumėte duomenų, atlaisvinkite arba išplėskite disko vietą." }, - "cluster-info": { - "service-id": "Paslaugos ID", - "service-type": "Paslaugos tipas", - "no-data": "Nėra duomenų" - }, "transport-messages": { "title": "Transporto žinutės", "info": "Visos žinutės, gautos iš įrenginių" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Dar nėra peržiūrėtų skydelių" }, "configured-features": { - "title": "Sukonfigūruotos funkcijos", - "info": "Funkcijų, kurioms reikia konfigūracijos, būsena", - "white-labeling-feature": "Prekės ženklo tinkinimas", - "email-feature": "El. paštas", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funkcija sukonfigūruota.\nSpustelėkite, kad nustatytumėte", "feature-not-configured": "Funkcija nesukonfigūruota.\nSpustelėkite, kad nustatytumėte" }, - "version-info": { - "title": "Versija", - "contact-us": "Susisiekite su mumis", - "current-version": "Dabartinė versija", - "current": "Dabartinė", - "available-version": "Prieinama versija", - "available": "Prieinama", - "upgrade": "Naujinti", - "version-is-up-to-date": "Versija yra naujausia" - }, - "license-info": { - "title": "Licencijos informacija", - "view-all": "Peržiūrėti visas", - "license-portal": "Licencijų portalas", - "devices-info": "{count} / { max, plural, =0 {∞ įrenginių} one {# įrenginys} few {# įrenginiai} other {# įrenginių} }", - "assets-info": "{count} / { max, plural, =0 {∞ turtų} one {# turtas} few {# turtai} other {# turtų} }", - "edges-info": "{count} / { max, plural, =0 {∞ Edge egzempliorių} one {# Edge egzempliorius} few {# Edge egzemplioriai} other {# Edge egzempliorių} }", - "dashboards-info": "{count} / { max, plural, =0 {∞ skydelių} one {# skydelis} few {# skydeliai} other {# skydelių} }", - "integrations-info": "{count} / { max, plural, =0 {∞ integracijų} one {# integracija} few {# integracijos} other {# integracijų} }", - "community-support": "Bendruomenės palaikymas", - "white-labeling": "Prekės ženklo tinkinimas", - "unlimited-datapoints-and-messages": "Neriboti duomenų taškai ir žinutės", - "unlimited-api-calls": "Neribotos API užklausos" - }, "usage-info": { "title": "Naudojimas", "entities": "Subjektai", diff --git a/ui-ngx/src/assets/locale/locale.constant-lv_LV.json b/ui-ngx/src/assets/locale/locale.constant-lv_LV.json index 36b3e0c6b1..41355162ef 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lv_LV.json +++ b/ui-ngx/src/assets/locale/locale.constant-lv_LV.json @@ -109,10 +109,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurēt ar MI", - "follow-up-prompt-placeholder": "Atbildēt...", - "sub-title": "Es varu palīdzēt jums iestatīt un pārvaldīt jūsu iekārtas, informācijas paneļus, aprēķinātos laukus, trauksmes noteikumus un paziņojumus — vienkārši aprakstiet, kas jums nepieciešams, un par pārējo parūpēšos es.", "new-chat": "Jauna saruna", - "no-chats": "Vēl nav sarunu", "today": "Šodien", "yesterday": "Vakardien", "last-7-days": "Pēdējās 7 dienas", @@ -120,16 +117,11 @@ "delete-chat-title": "Vai tiešām vēlaties dzēst '{{name}}'?", "delete-chat-text": "Visi sarunas ziņojumi tiks zaudēti", "delete-chat-confirm": "Jā, dzēst", - "action-approval-required": "Nepieciešams darbības apstiprinājums", "approve": "Apstiprināt", "deny": "Noraidīt", - "processing": "Apstrādā...", "approved": "Pabeigts", - "denied": "Noraidīts", "error": "Neizdevās", - "thinking": "Domāju...", - "rename-chat-title": "Pārdēvēt šo sarunu", - "main-title": "Sveiki! Es esmu jūsu MI asistents" + "thinking": "Domāju..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Ieteikt trauksmes noteikumus", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json index 3d5a4b2b22..8c3419bb4a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configureren met AI", - "follow-up-prompt-placeholder": "Antwoord...", - "sub-title": "Ik kan je helpen bij het instellen en beheren van je apparaten, dashboards, berekende velden, alarmregels en meldingen — beschrijf gewoon wat je nodig hebt en ik regel de rest.", "new-chat": "Nieuwe chat", - "no-chats": "Nog geen chats", "today": "Vandaag", "yesterday": "Gisteren", "last-7-days": "Afgelopen 7 dagen", @@ -703,17 +700,11 @@ "delete-chat-title": "Weet je zeker dat je '{{name}}' wilt verwijderen?", "delete-chat-text": "Alle chatberichten gaan verloren", "delete-chat-confirm": "Ja, verwijderen", - "action-approval-required": "Goedkeuring voor actie vereist", "approve": "Goedkeuren", - "approve-all": "Alle verdere acties goedkeuren", "deny": "Weigeren", - "processing": "Bezig met verwerken...", "approved": "Gereed", - "denied": "Geweigerd", "error": "Mislukt", "thinking": "Aan het nadenken...", - "connection-lost": "De verbinding met de AI-assistent is verbroken. Opnieuw verbinden...", - "reconnect-failed": "Kan niet opnieuw verbinden met de AI-assistent. Open de chat opnieuw om het antwoord te zien.", "ask-the-assistant": "Vraag het de AI-assistent", "send": "Verzenden", "new-line": "Nieuwe regel", @@ -740,9 +731,7 @@ "text": "Tekst", "file": "Bestand" }, - "rename-chat-title": "Deze chat hernoemen", - "export-chat": "Chat exporteren", - "main-title": "Hallo! Ik ben je AI-assistent" + "export-chat": "Chat exporteren" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Alarmregels voorstellen", @@ -11279,47 +11268,20 @@ "select-recaptcha-enterprise-service-account-file": "Sleep je accountreferentiesbestand hierheen" }, "solution-creator": { - "ai-solution-creator": "AI-oplossingsmaker", "describe-solution-you-want": "Beschrijf de oplossing die je wilt maken", - "enter-your-prompt": "Voer je prompt in", "target": "Doel", "install-solution": "Installeren", - "solution-overview": "Overzicht van oplossing: {{ name }}", - "dashboards-overview": "Overzicht van dashboards: {{ name }}", - "entity-profile": "Entiteitsprofiel", - "entity-profiles": "Entiteitsprofielen", - "name": "Naam", - "iam": "IAM", - "iam-full": "Identiteits- en toegangsbeheer", - "table-view": "Tabel", - "schema-view": "Schema", - "iam-info": "IAM-info", "operation": { "C": "Aanmaken", "R": "Lezen", "U": "Bijwerken", "D": "Verwijderen" }, - "alarm-info": "Alarminformatie", "description": "Beschrijving", - "data": "Gegevens", - "entity-info": "Entiteitsinformatie", - "calculated-field-info": "Informatie over berekend veld", - "field-type": "Veldtype", - "scope": "Bereik", "delete-alarm-title": "Dit voorgestelde alarm verwijderen?", "delete-alarm-text": "Dit alarm, voorgesteld op basis van je beschrijving, wordt niet toegevoegd aan de voorgestelde build van de oplossing.
Je kunt alarmen later altijd handmatig bewerken of opnieuw aanmaken. Deze actie kan niet ongedaan worden gemaakt.", - "basic-mode": "Basis", - "advanced-mode": "Geavanceerd", "create-solution": "Oplossing maken", "go-dashboard-manager": "Volgende: dashboardontwerp", - "success-generate-title": "De oplossing is klaar!", - "success-generate-sub-title": "Je kunt deze in je account installeren door op de knop hieronder te klikken", - "success-generate-install-title": "Oplossing geïnstalleerd!", - "success-generate-install-sub-title": "De-installeer eerst de bestaande instantie om de oplossing te bewerken", - "main-title": "Hallo! Ik ben je AI-assistent", - "sub-title": "Ik help je je eisen om te zetten in een volledig functionele IoT-oplossing.\nBeschrijf gewoon wat je wilt bereiken, en ik doe de rest.", - "solutions": "Oplossingen", "new-solution": "Nieuwe oplossing", "uninstall-solution": "De-installeren", "uninstall-solution-dialog-title": "Weet je zeker dat je ‘{{ name }}’ wilt de-installeren?", @@ -11329,12 +11291,8 @@ "delete-solution-text": "Al je gegevens gaan verloren", "delete-solution-confirm": "Ja, verwijderen", "copy-solution": "Oplossing kopiëren", - "expand-sidebar": "Zijbalk uitvouwen", - "collapse-sidebar": "Zijbalk samenvouwen", "solution-id": "Oplossings-ID", "solution-id-required": "Oplossings-ID is verplicht", - "rename-solution-title": "Naam van deze oplossing wijzigen", - "generate-again": "Opnieuw genereren", "skip-interview": "Interview overslaan", "update-solution": "Oplossing bijwerken", "finish-edit": "Bewerken voltooien", @@ -11344,8 +11302,6 @@ "water-metering": "Watermeting", "coffee-machine-monitoring": "Koffiemachinemonitoring", "fleet-geofencing": "Geofencing voor wagenpark", - "more-examples": "Meer voorbeelden", - "hide": "Verbergen", "solution-info": "Oplossingsinfo", "solution-info-with-name": "Oplossingsinfo: {{ name }}", "status": "Status", @@ -11358,14 +11314,8 @@ "info": "Info", "main-dashboard": "Hoofddashboard", "view-as": "Bekijken als {{ name }}", - "generated-by-calculated-field-name": "Gegenereerd door berekend veld ‘{{ name }}’", "estimate-wait-time": "Geschatte wachttijd is ~{{ time }}", - "analyzing-your-request": "Je verzoek wordt geanalyseerd...", "condition": "Voorwaarde", - "installing": "Oplossing wordt geïnstalleerd...", - "step-architecture-design": "Architectuurontwerp", - "step-dashboard-design": "Dashboardontwerp", - "step-solution-installation": "Installatie van oplossing", "step-reading-device-data": "Apparaatgegevens worden gelezen…", "step-analyzing-telemetry-attributes": "Telemetrie & attributen worden geanalyseerd…", "step-selecting-widgets": "Widgets voor je gegevens worden geselecteerd…", @@ -11397,11 +11347,7 @@ "step-loading-building-alarm-rules": "Alarmregels opbouwen…", "step-loading-assembling-dashboards": "Dashboards samenstellen…", "step-loading-preparing-states": "Toestanden voorbereiden…", - "step-loading-initializing-solution": "Oplossing initialiseren…", - "ai-credits": "AI-credits", - "ai-credits-update": "Abonnement wijzigen", - "ai-credits-usage": "AI-credits: {{ used }} van {{ max }} gebruikt", - "ai-credits-description": "Je hebt deze maand {{ used }} van je {{ max }} AI-credits gebruikt. De limiet wordt gereset op {{ date }}. Neem contact op met je systeembeheerder om je AI-credittegoed te verhogen." + "step-loading-initializing-solution": "Oplossing initialiseren…" }, "white-labeling": { "white-labeling": "White labeling", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Weinig schijfruimte beschikbaar. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen.", "disk-critical-text": "Kritiek weinig schijfruimte. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen." }, - "cluster-info": { - "service-id": "Service-ID", - "service-type": "Servicetype", - "no-data": "Geen gegevens" - }, "transport-messages": { "title": "Transportberichten", "info": "Alle berichten afkomstig van apparaten" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Nog geen laatst bekeken dashboards" }, "configured-features": { - "title": "Geconfigureerde functies", - "info": "Status van functies die configuratie vereisen", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Functie is geconfigureerd.\nKlik om in te stellen", "feature-not-configured": "Functie is niet geconfigureerd.\nKlik om in te stellen" }, - "version-info": { - "title": "Versie", - "contact-us": "Neem contact op", - "current-version": "Huidige versie", - "current": "Huidig", - "available-version": "Beschikbare versie", - "available": "Beschikbaar", - "upgrade": "Upgraden", - "version-is-up-to-date": "Versie is up-to-date" - }, - "license-info": { - "title": "Licentie-informatie", - "view-all": "Bekijk alles", - "license-portal": "Licentieportaal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Apparaten", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraties", - "community-support": "Community-ondersteuning", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Onbeperkte datapunten en berichten", - "unlimited-api-calls": "Onbeperkte API-aanroepen" - }, "usage-info": { "title": "Gebruik", "entities": "Entiteiten", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json index 3228981395..10abd98754 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configureren met AI", - "follow-up-prompt-placeholder": "Antwoord...", - "sub-title": "Ik kan je helpen bij het instellen en beheren van je apparaten, dashboards, berekende velden, alarmregels en meldingen — beschrijf gewoon wat je nodig hebt en ik regel de rest.", "new-chat": "Nieuwe chat", - "no-chats": "Nog geen chats", "today": "Vandaag", "yesterday": "Gisteren", "last-7-days": "Afgelopen 7 dagen", @@ -703,18 +700,12 @@ "delete-chat-title": "Weet je zeker dat je '{{name}}' wilt verwijderen?", "delete-chat-text": "Alle chatberichten gaan verloren", "delete-chat-confirm": "Ja, verwijderen", - "action-approval-required": "Goedkeuring voor actie vereist", "approve": "Goedkeuren", - "approve-all": "Alle verdere acties goedkeuren", "deny": "Weigeren", - "processing": "Bezig met verwerken...", "approved": "Gereed", - "denied": "Geweigerd", "error": "Mislukt", "thinking": "Aan het nadenken...", - "rename-chat-title": "Deze chat hernoemen", - "export-chat": "Chat exporteren", - "main-title": "Hallo! Ik ben je AI-assistent" + "export-chat": "Chat exporteren" }, "alarm": { "alarm": "Alarm", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Sleep je accountreferentiesbestand hierheen" }, "solution-creator": { - "ai-solution-creator": "AI-oplossingsmaker", "describe-solution-you-want": "Beschrijf de oplossing die je wilt maken", - "enter-your-prompt": "Voer je prompt in", "target": "Doel", "install-solution": "Installeren", - "solution-overview": "Overzicht van oplossing: {{ name }}", - "dashboards-overview": "Overzicht van dashboards: {{ name }}", - "entity-profile": "Entiteitsprofiel", - "entity-profiles": "Entiteitsprofielen", - "name": "Naam", - "iam": "IAM", - "iam-full": "Identiteits- en toegangsbeheer", - "table-view": "Tabel", - "schema-view": "Schema", - "iam-info": "IAM-info", "operation": { "C": "Aanmaken", "R": "Lezen", "U": "Bijwerken", "D": "Verwijderen" }, - "alarm-info": "Alarminformatie", "description": "Beschrijving", - "data": "Gegevens", - "entity-info": "Entiteitsinformatie", - "calculated-field-info": "Informatie over berekend veld", - "field-type": "Veldtype", - "scope": "Bereik", "delete-alarm-title": "Dit voorgestelde alarm verwijderen?", "delete-alarm-text": "Dit alarm, voorgesteld op basis van je beschrijving, wordt niet toegevoegd aan de voorgestelde build van de oplossing.
Je kunt alarmen later altijd handmatig bewerken of opnieuw aanmaken. Deze actie kan niet ongedaan worden gemaakt.", - "basic-mode": "Basis", - "advanced-mode": "Geavanceerd", "create-solution": "Oplossing maken", "go-dashboard-manager": "Volgende: dashboardontwerp", - "success-generate-title": "De oplossing is klaar!", - "success-generate-sub-title": "Je kunt deze in je account installeren door op de knop hieronder te klikken", - "success-generate-install-title": "Oplossing geïnstalleerd!", - "success-generate-install-sub-title": "De-installeer eerst de bestaande instantie om de oplossing te bewerken", - "main-title": "Hallo! Ik ben je AI-assistent", - "sub-title": "Ik help je je eisen om te zetten in een volledig functionele IoT-oplossing.\nBeschrijf gewoon wat je wilt bereiken, en ik doe de rest.", - "solutions": "Oplossingen", "new-solution": "Nieuwe oplossing", "uninstall-solution": "De-installeren", "uninstall-solution-dialog-title": "Weet je zeker dat je ‘{{ name }}’ wilt de-installeren?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Al je gegevens gaan verloren", "delete-solution-confirm": "Ja, verwijderen", "copy-solution": "Oplossing kopiëren", - "expand-sidebar": "Zijbalk uitvouwen", - "collapse-sidebar": "Zijbalk samenvouwen", "solution-id": "Oplossings-ID", "solution-id-required": "Oplossings-ID is verplicht", - "rename-solution-title": "Naam van deze oplossing wijzigen", - "generate-again": "Opnieuw genereren", "skip-interview": "Interview overslaan", "update-solution": "Oplossing bijwerken", "finish-edit": "Bewerken voltooien", @@ -11298,8 +11258,6 @@ "water-metering": "Watermeting", "coffee-machine-monitoring": "Koffiemachinemonitoring", "fleet-geofencing": "Geofencing voor wagenpark", - "more-examples": "Meer voorbeelden", - "hide": "Verbergen", "solution-info": "Oplossingsinfo", "solution-info-with-name": "Oplossingsinfo: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Hoofddashboard", "view-as": "Bekijken als {{ name }}", - "generated-by-calculated-field-name": "Gegenereerd door berekend veld ‘{{ name }}’", "estimate-wait-time": "Geschatte wachttijd is ~{{ time }}", - "analyzing-your-request": "Je verzoek wordt geanalyseerd...", "condition": "Voorwaarde", - "installing": "Oplossing wordt geïnstalleerd...", - "step-architecture-design": "Architectuurontwerp", - "step-dashboard-design": "Dashboardontwerp", - "step-solution-installation": "Installatie van oplossing", "step-reading-device-data": "Apparaatgegevens worden gelezen…", "step-analyzing-telemetry-attributes": "Telemetrie & attributen worden geanalyseerd…", "step-selecting-widgets": "Widgets voor je gegevens worden geselecteerd…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarmregels opbouwen…", "step-loading-assembling-dashboards": "Dashboards samenstellen…", "step-loading-preparing-states": "Toestanden voorbereiden…", - "step-loading-initializing-solution": "Oplossing initialiseren…", - "ai-credits": "AI-credits", - "ai-credits-update": "Abonnement wijzigen", - "ai-credits-usage": "AI-credits: {{ used }} van {{ max }} gebruikt", - "ai-credits-description": "Je hebt deze maand {{ used }} van je {{ max }} AI-credits gebruikt. De limiet wordt gereset op {{ date }}. Neem contact op met je systeembeheerder om je AI-credittegoed te verhogen." + "step-loading-initializing-solution": "Oplossing initialiseren…" }, "markdown": { "edit": "Bewerken", @@ -13781,11 +13729,6 @@ "disk-warning-text": "Weinig schijfruimte beschikbaar. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen.", "disk-critical-text": "Kritieke schijfruimte. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen." }, - "cluster-info": { - "service-id": "Service-ID", - "service-type": "Servicetype", - "no-data": "Geen gegevens" - }, "transport-messages": { "title": "Transportberichten", "info": "Alle berichten afkomstig van apparaten" @@ -13824,41 +13767,9 @@ "no-last-viewed-dashboards": "Nog geen laatst bekeken dashboards" }, "configured-features": { - "title": "Geconfigureerde functies", - "info": "Status van functies die configuratie vereisen", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Functie is geconfigureerd.\nKlik om in te stellen", "feature-not-configured": "Functie is niet geconfigureerd.\nKlik om in te stellen" }, - "version-info": { - "title": "Versie", - "contact-us": "Neem contact op", - "current-version": "Huidige versie", - "current": "Huidig", - "available-version": "Beschikbare versie", - "available": "Beschikbaar", - "upgrade": "Upgraden", - "version-is-up-to-date": "Versie is up-to-date" - }, - "license-info": { - "title": "Licentie-informatie", - "view-all": "Bekijk alles", - "license-portal": "Licentieportaal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Apparaten", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraties", - "community-support": "Community-ondersteuning", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Onbeperkte datapunten en berichten", - "unlimited-api-calls": "Onbeperkte API-aanroepen" - }, "usage-info": { "title": "Gebruik", "entities": "Entiteiten", diff --git a/ui-ngx/src/assets/locale/locale.constant-no_NO.json b/ui-ngx/src/assets/locale/locale.constant-no_NO.json index a4436625e7..023f254b81 100644 --- a/ui-ngx/src/assets/locale/locale.constant-no_NO.json +++ b/ui-ngx/src/assets/locale/locale.constant-no_NO.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurer med AI", - "follow-up-prompt-placeholder": "Svar...", - "sub-title": "Jeg kan hjelpe deg med å sette opp og administrere enhetene, dashbordene, beregnede felt, alarmregler og varsler dine — bare beskriv hva du trenger, så ordner jeg resten.", "new-chat": "Ny chat", - "no-chats": "Ingen chatter ennå", "today": "I dag", "yesterday": "I går", "last-7-days": "Siste 7 dager", @@ -703,20 +700,12 @@ "delete-chat-title": "Er du sikker på at du vil slette '{{name}}'?", "delete-chat-text": "Alle chatmeldinger vil gå tapt", "delete-chat-confirm": "Ja, slett", - "action-approval-required": "Godkjenning av handling kreves", "approve": "Godkjenn", - "approve-all": "Godkjenn alle videre handlinger", "deny": "Avslå", - "processing": "Behandler...", "approved": "Ferdig", - "denied": "Avslått", "error": "Mislyktes", "thinking": "Tenker...", - "connection-lost": "Tilkoblingen til AI-assistenten ble brutt. Kobler til på nytt...", - "reconnect-failed": "Kunne ikke koble til AI-assistenten på nytt. Åpne chatten igjen for å se svaret.", - "rename-chat-title": "Gi nytt navn til denne chatten", - "export-chat": "Eksporter chat", - "main-title": "Hei! Jeg er AI-assistenten din" + "export-chat": "Eksporter chat" }, "alarm": { "alarm": "Alarm", @@ -11247,47 +11236,20 @@ "select-recaptcha-enterprise-service-account-file": "Dra og slipp filen med kontoopplysninger" }, "solution-creator": { - "ai-solution-creator": "AI-løsningsbygger", "describe-solution-you-want": "Beskriv løsningen du vil lage", - "enter-your-prompt": "Skriv inn prompten din", "target": "Mål", "install-solution": "Installer", - "solution-overview": "Løsningsoversikt: {{ name }}", - "dashboards-overview": "Dashbordoversikt: {{ name }}", - "entity-profile": "Entitetsprofil", - "entity-profiles": "Entitetsprofiler", - "name": "Navn", - "iam": "IAM", - "iam-full": "Identitets- og tilgangsstyring", - "table-view": "Tabell", - "schema-view": "Skjema", - "iam-info": "IAM-info", "operation": { "C": "Opprett", "R": "Les", "U": "Oppdater", "D": "Slett" }, - "alarm-info": "Alarminfo", "description": "Beskrivelse", - "data": "Data", - "entity-info": "Entitetsinfo", - "calculated-field-info": "Info om beregnet felt", - "field-type": "Felttype", - "scope": "Omfang", "delete-alarm-title": "Slette denne foreslåtte alarmen?", "delete-alarm-text": "Denne alarmen, som ble foreslått basert på beskrivelsen din, blir ikke lagt til i den foreslåtte løsningen.
Du kan alltid redigere eller opprette alarmer på nytt manuelt senere. Denne handlingen kan ikke angres.", - "basic-mode": "Grunnleggende", - "advanced-mode": "Avansert", "create-solution": "Opprett løsning", "go-dashboard-manager": "Neste: Dashborddesign", - "success-generate-title": "Løsningen er klar!", - "success-generate-sub-title": "Du kan installere den på kontoen din ved å klikke på knappen nedenfor", - "success-generate-install-title": "Løsningen er installert!", - "success-generate-install-sub-title": "For å redigere løsningen må du først avinstallere den eksisterende instansen", - "main-title": "Hei! Jeg er AI-assistenten din", - "sub-title": "Jeg hjelper deg med å gjøre kravene dine om til en fullt fungerende IoT-løsning.\nBare beskriv hva du vil oppnå, så tar jeg meg av resten.", - "solutions": "Løsninger", "new-solution": "Ny løsning", "uninstall-solution": "Avinstaller", "uninstall-solution-dialog-title": "Er du sikker på at du vil avinstallere ‘{{ name }}’?", @@ -11297,12 +11259,8 @@ "delete-solution-text": "Alle dataene dine vil gå tapt", "delete-solution-confirm": "Ja, slett", "copy-solution": "Kopier løsning", - "expand-sidebar": "Utvid sidepanel", - "collapse-sidebar": "Skjul sidepanel", "solution-id": "Løsnings-ID", "solution-id-required": "Løsnings-ID er påkrevd", - "rename-solution-title": "Gi nytt navn til denne løsningen", - "generate-again": "Generer på nytt", "skip-interview": "Hopp over intervjuet", "update-solution": "Oppdater løsning", "finish-edit": "Fullfør redigering", @@ -11312,8 +11270,6 @@ "water-metering": "Vannmåling", "coffee-machine-monitoring": "Overvåking av kaffemaskiner", "fleet-geofencing": "Geofencing for kjøretøyflåte", - "more-examples": "Flere eksempler", - "hide": "Skjul", "solution-info": "Løsningsinformasjon", "solution-info-with-name": "Løsningsinformasjon: {{ name }}", "status": "Status", @@ -11326,14 +11282,8 @@ "info": "Info", "main-dashboard": "Hoveddashbord", "view-as": "Vis som {{ name }}", - "generated-by-calculated-field-name": "Generert av det beregnede feltet ‘{{ name }}’", "estimate-wait-time": "Estimert ventetid er ~{{ time }}", - "analyzing-your-request": "Analyserer forespørselen din...", "condition": "Betingelse", - "installing": "Installerer løsningen...", - "step-architecture-design": "Arkitekturdesign", - "step-dashboard-design": "Dashborddesign", - "step-solution-installation": "Installasjon av løsningen", "step-reading-device-data": "Leser enhetsdata…", "step-analyzing-telemetry-attributes": "Analyserer telemetri og attributter…", "step-selecting-widgets": "Velger widgeter for dataene dine…", @@ -11365,11 +11315,7 @@ "step-loading-building-alarm-rules": "Bygger alarmregler…", "step-loading-assembling-dashboards": "Setter sammen dashbord…", "step-loading-preparing-states": "Forbereder tilstander…", - "step-loading-initializing-solution": "Initialiserer løsningen…", - "ai-credits": "AI-kreditter", - "ai-credits-update": "Bytt plan", - "ai-credits-usage": "AI-kreditter: {{ used }} av {{ max }} brukt", - "ai-credits-description": "Du har brukt {{ used }} av dine {{ max }} AI-kreditter denne måneden. Grensen tilbakestilles {{ date }}. Kontakt systemadministratoren for å øke AI-kredittkvoten din." + "step-loading-initializing-solution": "Initialiserer løsningen…" }, "markdown": { "edit": "Rediger", @@ -13795,11 +13741,6 @@ "disk-warning-text": "Lite tilgjengelig diskplass. For å unngå datatap, frigjør eller utvid diskplassen.", "disk-critical-text": "Kritisk lite diskplass. For å unngå datatap, frigjør eller utvid diskplassen." }, - "cluster-info": { - "service-id": "Tjeneste-ID", - "service-type": "Tjenestetype", - "no-data": "Ingen data" - }, "transport-messages": { "title": "Transportmeldinger", "info": "Alle meldinger mottatt fra enheter" @@ -13838,41 +13779,9 @@ "no-last-viewed-dashboards": "Ingen nylig viste dashbord" }, "configured-features": { - "title": "Konfigurerte funksjoner", - "info": "Status for funksjoner som krever konfigurasjon", - "white-labeling-feature": "White labeling", - "email-feature": "E-post", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funksjonen er konfigurert.\nKlikk for å sette opp", "feature-not-configured": "Funksjonen er ikke konfigurert.\nKlikk for å sette opp" }, - "version-info": { - "title": "Versjon", - "contact-us": "Kontakt oss", - "current-version": "Gjeldende versjon", - "current": "Gjeldende", - "available-version": "Tilgjengelig versjon", - "available": "Tilgjengelig", - "upgrade": "Oppgrader", - "version-is-up-to-date": "Versjonen er oppdatert" - }, - "license-info": { - "title": "Lisensinformasjon", - "view-all": "Vis alle", - "license-portal": "Lisensportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } enheter", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } eiendeler", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge-instanser", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } dashbord", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integrasjoner", - "community-support": "Fellesskapsstøtte", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Ubegrensede datapunkter og meldinger", - "unlimited-api-calls": "Ubegrensede API-kall" - }, "usage-info": { "title": "Bruk", "entities": "Entiteter", diff --git a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json index 769c74e48c..419f7552a6 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json +++ b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Skonfiguruj z AI", - "follow-up-prompt-placeholder": "Odpowiedz...", - "sub-title": "Pomogę Ci skonfigurować Twoje urządzenia, pulpity, pola obliczeniowe, reguły alarmów i powiadomienia oraz zarządzać nimi — wystarczy, że opiszesz, czego potrzebujesz, a ja zajmę się resztą.", "new-chat": "Nowy czat", - "no-chats": "Brak czatów", "today": "Dzisiaj", "yesterday": "Wczoraj", "last-7-days": "Ostatnie 7 dni", @@ -703,17 +700,11 @@ "delete-chat-title": "Czy na pewno chcesz usunąć „{{name}}”?", "delete-chat-text": "Wszystkie wiadomości czatu zostaną utracone", "delete-chat-confirm": "Tak, usuń", - "action-approval-required": "Wymagane zatwierdzenie akcji", "approve": "Zatwierdź", - "approve-all": "Zatwierdź wszystkie kolejne działania", "deny": "Odrzuć", - "processing": "Przetwarzanie...", "approved": "Gotowe", - "denied": "Odrzucone", "error": "Niepowodzenie", "thinking": "Myślę...", - "connection-lost": "Utracono połączenie z asystentem AI. Ponowne łączenie...", - "reconnect-failed": "Nie udało się ponownie połączyć z asystentem AI. Otwórz czat ponownie, aby zobaczyć odpowiedź.", "ask-the-assistant": "Zapytaj asystenta AI", "send": "Wyślij", "new-line": "Nowy wiersz", @@ -740,9 +731,7 @@ "text": "Tekst", "file": "Plik" }, - "rename-chat-title": "Zmień nazwę tego czatu", - "export-chat": "Eksportuj czat", - "main-title": "Cześć! Jestem Twoim asystentem AI" + "export-chat": "Eksportuj czat" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Zaproponuj reguły alarmów", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "Przeciągnij i upuść plik z danymi uwierzytelniającymi Twojego konta" }, "solution-creator": { - "ai-solution-creator": "Kreator rozwiązań AI", "describe-solution-you-want": "Opisz rozwiązanie, które chcesz utworzyć", - "enter-your-prompt": "Wprowadź prompt", "target": "Cel", "install-solution": "Zainstaluj", - "solution-overview": "Przegląd rozwiązania: {{ name }}", - "dashboards-overview": "Przegląd pulpitów: {{ name }}", - "entity-profile": "Profil obiektu", - "entity-profiles": "Profile obiektów", - "name": "Nazwa", - "iam": "IAM", - "iam-full": "Zarządzanie tożsamością i dostępem", - "table-view": "Tabela", - "schema-view": "Schemat", - "iam-info": "Informacje o IAM", "operation": { "C": "Utwórz", "R": "Odczytaj", "U": "Aktualizuj", "D": "Usuń" }, - "alarm-info": "Informacje o alarmie", "description": "Opis", - "data": "Dane", - "entity-info": "Informacje o obiekcie", - "calculated-field-info": "Informacje o polu obliczeniowym", - "field-type": "Typ pola", - "scope": "Zakres", "delete-alarm-title": "Czy chcesz usunąć ten sugerowany alarm?", "delete-alarm-text": "Ten alarm, zasugerowany na podstawie Twojego opisu, nie zostanie dodany do proponowanej wersji rozwiązania.
Alarmy możesz zawsze później edytować lub ręcznie utworzyć ponownie. Tej akcji nie można cofnąć.", - "basic-mode": "Podstawowy", - "advanced-mode": "Zaawansowany", "create-solution": "Utwórz rozwiązanie", "go-dashboard-manager": "Dalej: projekt pulpitu", - "success-generate-title": "Rozwiązanie jest gotowe!", - "success-generate-sub-title": "Możesz je zainstalować na swoim koncie, klikając przycisk poniżej", - "success-generate-install-title": "Rozwiązanie zostało zainstalowane!", - "success-generate-install-sub-title": "Aby edytować rozwiązanie, najpierw odinstaluj istniejącą instancję", - "main-title": "Cześć! Jestem Twoim asystentem AI", - "sub-title": "Pomagam Ci przekształcić Twoje wymagania w w pełni funkcjonalne rozwiązanie IoT.\nPo prostu opisz, co chcesz osiągnąć, a ja zajmę się resztą.", - "solutions": "Rozwiązania", "new-solution": "Nowe rozwiązanie", "uninstall-solution": "Odinstaluj", "uninstall-solution-dialog-title": "Czy na pewno chcesz odinstalować „{{ name }}”?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "Wszystkie Twoje dane zostaną utracone", "delete-solution-confirm": "Tak, usuń", "copy-solution": "Kopiuj rozwiązanie", - "expand-sidebar": "Rozwiń panel boczny", - "collapse-sidebar": "Zwiń panel boczny", "solution-id": "ID rozwiązania", "solution-id-required": "ID rozwiązania jest wymagane", - "rename-solution-title": "Zmień nazwę tego rozwiązania", - "generate-again": "Wygeneruj ponownie", "skip-interview": "Pomiń wywiad", "update-solution": "Aktualizuj rozwiązanie", "finish-edit": "Zakończ edycję", @@ -11338,8 +11296,6 @@ "water-metering": "Pomiar zużycia wody", "coffee-machine-monitoring": "Monitorowanie ekspresów do kawy", "fleet-geofencing": "Geofencing floty", - "more-examples": "Więcej przykładów", - "hide": "Ukryj", "solution-info": "Informacje o rozwiązaniu", "solution-info-with-name": "Informacje o rozwiązaniu: {{ name }}", "status": "Status", @@ -11352,14 +11308,8 @@ "info": "Informacje", "main-dashboard": "Pulpit główny", "view-as": "Wyświetl jako {{ name }}", - "generated-by-calculated-field-name": "Wygenerowano przez pole obliczeniowe „{{ name }}”", "estimate-wait-time": "Szacowany czas oczekiwania: ~{{ time }}", - "analyzing-your-request": "Analizowanie Twojego zapytania...", "condition": "Warunek", - "installing": "Instalowanie rozwiązania...", - "step-architecture-design": "Projekt architektury", - "step-dashboard-design": "Projekt pulpitu", - "step-solution-installation": "Instalacja rozwiązania", "step-reading-device-data": "Odczytywanie danych urządzenia…", "step-analyzing-telemetry-attributes": "Analizowanie telemetrii i atrybutów…", "step-selecting-widgets": "Wybieranie widżetów dla Twoich danych…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "Tworzenie reguł alarmów…", "step-loading-assembling-dashboards": "Składanie pulpitów…", "step-loading-preparing-states": "Przygotowywanie stanów…", - "step-loading-initializing-solution": "Inicjowanie rozwiązania…", - "ai-credits": "Kredyty AI", - "ai-credits-update": "Zmień plan", - "ai-credits-usage": "Kredyty AI: wykorzystano {{ used }} z {{ max }}", - "ai-credits-description": "W tym miesiącu wykorzystano {{ used }} z {{ max }} Twoich kredytów AI. Limit zostanie zresetowany {{ date }}. Aby zwiększyć limit kredytów AI, skontaktuj się z administratorem systemu." + "step-loading-initializing-solution": "Inicjowanie rozwiązania…" }, "markdown": { "edit": "Edytuj", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Kończy się miejsce na dysku. Aby zapobiec utracie danych, zwolnij lub zwiększ miejsce na dysku.", "disk-critical-text": "Krytycznie mało miejsca na dysku. Aby zapobiec utracie danych, zwolnij lub zwiększ miejsce na dysku." }, - "cluster-info": { - "service-id": "Identyfikator usługi", - "service-type": "Rodzaj usługi", - "no-data": "Brak danych" - }, "transport-messages": { "title": "Wiadomości transportowe", "info": "Wszystkie wiadomości pochodzące z urządzeń" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Nie ma jeszcze ostatnio oglądanych pulpitów" }, "configured-features": { - "title": "Skonfigurowane funkcje", - "info": "Stan funkcji wymagających konfiguracji", - "white-labeling-feature": "Branding", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funkcja jest skonfigurowana.\nKliknij, aby skonfigurować", "feature-not-configured": "Funkcja nie jest skonfigurowana.\nKliknij, aby skonfigurować" }, - "version-info": { - "title": "Wersja", - "contact-us": "Skontaktuj się z nami", - "current-version": "Bieżąca wersja", - "current": "Bieżąca", - "available-version": "Dostępna wersja", - "available": "Dostępna", - "upgrade": "Uaktualnij", - "version-is-up-to-date": "Wersja jest aktualna" - }, - "license-info": { - "title": "Informacje o licencji", - "view-all": "Pokaż wszystkie", - "license-portal": "Portal licencyjny", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } urządzeń", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } zasobów", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } instancji Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } pulpitów", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integracji", - "community-support": "Pomoc społeczności", - "white-labeling": "Branding", - "unlimited-datapoints-and-messages": "Nieograniczone punkty danych i wiadomości", - "unlimited-api-calls": "Nieograniczone wywołania API" - }, "usage-info": { "title": "Wykorzystanie", "entities": "Obiekty", diff --git a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json index d7a2cdf625..c133e839ea 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json +++ b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurar com IA", - "follow-up-prompt-placeholder": "Responder...", - "sub-title": "Posso ajudá-lo a configurar e gerenciar seus dispositivos, dashboards, campos calculados, regras de alarme e notificações — basta descrever o que você precisa e eu cuido do resto.", "new-chat": "Novo chat", - "no-chats": "Nenhum chat ainda", "today": "Hoje", "yesterday": "Ontem", "last-7-days": "Últimos 7 dias", @@ -703,18 +700,12 @@ "delete-chat-title": "Tem certeza de que deseja excluir '{{name}}'?", "delete-chat-text": "Todas as mensagens do chat serão perdidas", "delete-chat-confirm": "Sim, excluir", - "action-approval-required": "Aprovação da ação necessária", "approve": "Aprovar", - "approve-all": "Aprovar todas as próximas ações", "deny": "Negar", - "processing": "Processando...", "approved": "Concluído", - "denied": "Negado", "error": "Falhou", "thinking": "Pensando...", - "rename-chat-title": "Renomear este chat", - "export-chat": "Exportar chat", - "main-title": "Olá! Eu sou seu assistente de IA" + "export-chat": "Exportar chat" }, "alarm": { "alarm": "Alarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Arraste e solte seu arquivo de credenciais da conta" }, "solution-creator": { - "ai-solution-creator": "Criador de soluções com IA", "describe-solution-you-want": "Descreva a solução que você deseja criar", - "enter-your-prompt": "Insira seu prompt", "target": "Destino", "install-solution": "Instalar", - "solution-overview": "Visão geral da solução: {{ name }}", - "dashboards-overview": "Visão geral dos dashboards: {{ name }}", - "entity-profile": "Perfil de entidade", - "entity-profiles": "Perfis de entidade", - "name": "Nome", - "iam": "IAM", - "iam-full": "Gerenciamento de identidade e acesso", - "table-view": "Tabela", - "schema-view": "Esquema", - "iam-info": "Informações de IAM", "operation": { "C": "Criar", "R": "Ler", "U": "Modificar", "D": "Excluir" }, - "alarm-info": "Informações do alarme", "description": "Descrição", - "data": "Dados", - "entity-info": "Informações da entidade", - "calculated-field-info": "Informações do campo calculado", - "field-type": "Tipo de campo", - "scope": "Escopo", "delete-alarm-title": "Excluir este alarme sugerido?", "delete-alarm-text": "Este alarme, sugerido com base na sua descrição, não será adicionado à solução proposta.
Você sempre pode editar ou recriar alarmes manualmente mais tarde. Esta ação não pode ser desfeita.", - "basic-mode": "Básico", - "advanced-mode": "Avançado", "create-solution": "Criar solução", "go-dashboard-manager": "Próximo: design do dashboard", - "success-generate-title": "A solução está pronta!", - "success-generate-sub-title": "Você pode instalá-la na sua conta clicando no botão abaixo", - "success-generate-install-title": "Solução instalada!", - "success-generate-install-sub-title": "Para editar a solução, primeiro desinstale a instância existente", - "main-title": "Olá! Sou seu assistente de IA", - "sub-title": "Ajudo você a transformar seus requisitos em uma solução de IoT totalmente funcional.\nBasta descrever o que deseja alcançar, e eu cuido do resto.", - "solutions": "Soluções", "new-solution": "Nova solução", "uninstall-solution": "Desinstalar", "uninstall-solution-dialog-title": "Tem certeza de que deseja desinstalar ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Todos os seus dados serão perdidos", "delete-solution-confirm": "Sim, excluir", "copy-solution": "Copiar solução", - "expand-sidebar": "Expandir barra lateral", - "collapse-sidebar": "Recolher barra lateral", "solution-id": "ID da solução", "solution-id-required": "O ID da solução é obrigatório", - "rename-solution-title": "Renomear esta solução", - "generate-again": "Gerar novamente", "skip-interview": "Ignorar entrevista", "update-solution": "Atualizar solução", "finish-edit": "Concluir edição", @@ -11298,8 +11258,6 @@ "water-metering": "Medição de água", "coffee-machine-monitoring": "Monitoramento de máquinas de café", "fleet-geofencing": "Geofencing de frota", - "more-examples": "Mais exemplos", - "hide": "Ocultar", "solution-info": "Informações da solução", "solution-info-with-name": "Informações da solução: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Informações", "main-dashboard": "Dashboard principal", "view-as": "Visualizar como {{ name }}", - "generated-by-calculated-field-name": "Gerado pelo campo calculado ‘{{ name }}’", "estimate-wait-time": "O tempo de espera estimado é de ~{{ time }}", - "analyzing-your-request": "Analisando sua solicitação...", "condition": "Condição", - "installing": "Instalando a solução...", - "step-architecture-design": "Design da arquitetura", - "step-dashboard-design": "Design do dashboard", - "step-solution-installation": "Instalação da solução", "step-reading-device-data": "Lendo dados do dispositivo…", "step-analyzing-telemetry-attributes": "Analisando telemetria e atributos…", "step-selecting-widgets": "Selecionando widgets para seus dados…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construindo regras de alarme…", "step-loading-assembling-dashboards": "Montando dashboards…", "step-loading-preparing-states": "Preparando estados…", - "step-loading-initializing-solution": "Inicializando a solução…", - "ai-credits": "Créditos de IA", - "ai-credits-update": "Alterar plano", - "ai-credits-usage": "Créditos de IA: {{ used }} de {{ max }} usados", - "ai-credits-description": "Você usou {{ used }} dos seus {{ max }} créditos de IA este mês. O limite será redefinido em {{ date }}. Para aumentar sua cota de créditos de IA, entre em contato com o administrador do sistema." + "step-loading-initializing-solution": "Inicializando a solução…" }, "markdown": { "edit": "Editar", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Pouco espaço em disco. Para evitar perda de dados, libere ou expanda o espaço em disco.", "disk-critical-text": "Espaço em disco criticamente baixo. Para evitar perda de dados, libere ou expanda o espaço em disco." }, - "cluster-info": { - "service-id": "Id do serviço", - "service-type": "Tipo de serviço", - "no-data": "Sem dados" - }, "transport-messages": { "title": "Mensagens de transporte", "info": "Todas as mensagens recebidas dos dispositivos" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Nenhum Dashboard visualizado recentemente" }, "configured-features": { - "title": "Recursos configurados", - "info": "Status dos recursos que requerem configuração", - "white-labeling-feature": "Personalização de marca", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Recurso está configurado.\nClique para configurar", "feature-not-configured": "Recurso não está configurado.\nClique para configurar" }, - "version-info": { - "title": "Versão", - "contact-us": "Fale conosco", - "current-version": "Versão atual", - "current": "Atual", - "available-version": "Versão disponível", - "available": "Disponível", - "upgrade": "Atualizar versão", - "version-is-up-to-date": "Versão está atualizada" - }, - "license-info": { - "title": "Informações de licença", - "view-all": "Ver todos", - "license-portal": "Portal de licenças", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivos", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Ativos", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrações", - "community-support": "Suporte da comunidade", - "white-labeling": "Personalização de marca", - "unlimited-datapoints-and-messages": "Datapoints e mensagens ilimitados", - "unlimited-api-calls": "Chamadas de API ilimitadas" - }, "usage-info": { "title": "Uso", "entities": "Entidades", diff --git a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json index 3e904b23b0..1b895dc926 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json +++ b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json @@ -111,10 +111,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurează cu IA", - "follow-up-prompt-placeholder": "Răspunde...", - "sub-title": "Vă pot ajuta să configurați și să gestionați dispozitivele, tablourile de bord, câmpurile calculate, regulile de alarmă și notificările — descrieți doar ce aveți nevoie, iar eu mă ocup de rest.", "new-chat": "Conversație nouă", - "no-chats": "Încă nu există conversații", "today": "Astăzi", "yesterday": "Ieri", "last-7-days": "Ultimele 7 zile", @@ -122,16 +119,11 @@ "delete-chat-title": "Sigur vrei să ștergi '{{name}}'?", "delete-chat-text": "Toate mesajele din conversație vor fi pierdute", "delete-chat-confirm": "Da, șterge", - "action-approval-required": "Este necesară aprobarea acțiunii", "approve": "Aprobă", "deny": "Refuză", - "processing": "Procesare...", "approved": "Terminat", - "denied": "Refuzat", "error": "Eșuat", - "thinking": "Mă gândesc...", - "rename-chat-title": "Redenumește această conversație", - "main-title": "Bună! Sunt asistentul tău IA" + "thinking": "Mă gândesc..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Sugerează reguli de alarmă", diff --git a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json index db258613f3..8e62ad240a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json +++ b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfiguriraj z AI", - "follow-up-prompt-placeholder": "Odgovori...", - "sub-title": "Pomagam vam surove telemetrične podatke spremeniti v smiselne uvide. Preprosto opišite, kaj želite doseči, in jaz bom poskrbel za ostalo.", "new-chat": "Nov klepet", - "no-chats": "Še ni klepetov", "today": "Danes", "yesterday": "Včeraj", "last-7-days": "Zadnjih 7 dni", @@ -703,17 +700,11 @@ "delete-chat-title": "Ali ste prepričani, da želite izbrisati »{{name}}«?", "delete-chat-text": "Vsa sporočila klepeta bodo izgubljena", "delete-chat-confirm": "Da, izbriši", - "action-approval-required": "Potrebna je odobritev dejanja", "approve": "Odobri", - "approve-all": "Odobri vsa nadaljnja dejanja", "deny": "Zavrni", - "processing": "Obdelovanje...", "approved": "Končano", - "denied": "Zavrnjeno", "error": "Ni uspelo", "thinking": "Razmišljam...", - "connection-lost": "Povezava s pomočnikom AI je bila prekinjena. Ponovno vzpostavljanje povezave...", - "reconnect-failed": "Ponovna povezava s pomočnikom AI ni uspela. Znova odprite klepet, da vidite njegov odgovor.", "ask-the-assistant": "Vprašaj pomočnika AI", "send": "Pošlji", "new-line": "Nova vrstica", @@ -740,9 +731,7 @@ "text": "Besedilo", "file": "Datoteka" }, - "rename-chat-title": "Preimenuj ta klepet", - "export-chat": "Izvozi klepet", - "main-title": "Pozdravljeni! Jaz sem vaš AI-pomočnik" + "export-chat": "Izvozi klepet" }, "alarm": { "alarm": "Alarm", @@ -11344,47 +11333,20 @@ "select-recaptcha-enterprise-service-account-file": "Povlecite in spustite datoteko s poverilnicami računa" }, "solution-creator": { - "ai-solution-creator": "Ustvarjalnik rešitev AI", "describe-solution-you-want": "Opišite rešitev, ki jo želite ustvariti", - "enter-your-prompt": "Vnesite poziv", "target": "Cilj", "install-solution": "Namesti", - "solution-overview": "Pregled rešitve: {{ name }}", - "dashboards-overview": "Pregled nadzornih plošč: {{ name }}", - "entity-profile": "Profil entitete", - "entity-profiles": "Profili entitet", - "name": "Ime", - "iam": "IAM", - "iam-full": "Upravljanje identitet in dostopa", - "table-view": "Tabela", - "schema-view": "Shema", - "iam-info": "Informacije o IAM", "operation": { "C": "Ustvari", "R": "Preberi", "U": "Posodobi", "D": "Izbriši" }, - "alarm-info": "Informacije o alarmu", "description": "Opis", - "data": "Podatki", - "entity-info": "Informacije o entiteti", - "calculated-field-info": "Informacije o izračunanem polju", - "field-type": "Vrsta polja", - "scope": "Obseg", "delete-alarm-title": "Ali želite izbrisati ta predlagani alarm?", "delete-alarm-text": "Ta alarm, predlagan na podlagi vašega opisa, ne bo dodan v predlagano rešitev.
Alarme lahko kadar koli pozneje ročno uredite ali znova ustvarite. Tega dejanja ni mogoče razveljaviti.", - "basic-mode": "Osnovno", - "advanced-mode": "Napredno", "create-solution": "Ustvari rešitev", "go-dashboard-manager": "Naprej: oblikovanje nadzorne plošče", - "success-generate-title": "Rešitev je pripravljena!", - "success-generate-sub-title": "Namestite jo lahko v svoj račun s klikom na spodnji gumb", - "success-generate-install-title": "Rešitev je nameščena!", - "success-generate-install-sub-title": "Če želite urediti rešitev, najprej odstranite obstoječo namestitev", - "main-title": "Pozdravljeni! Jaz sem vaš AI-pomočnik", - "sub-title": "Pomagam vam pretvoriti vaše zahteve v popolnoma delujočo rešitev IoT.\nSamo opišite, kaj želite doseči, za vse drugo pa bom poskrbel jaz.", - "solutions": "Rešitve", "new-solution": "Nova rešitev", "uninstall-solution": "Odstrani namestitev", "uninstall-solution-dialog-title": "Ali ste prepričani, da želite odstraniti »{{ name }}«?", @@ -11394,12 +11356,8 @@ "delete-solution-text": "Vsi vaši podatki bodo izgubljeni", "delete-solution-confirm": "Da, izbriši", "copy-solution": "Kopiraj rešitev", - "expand-sidebar": "Razširi stransko vrstico", - "collapse-sidebar": "Strni stransko vrstico", "solution-id": "ID rešitve", "solution-id-required": "ID rešitve je obvezen", - "rename-solution-title": "Preimenuj to rešitev", - "generate-again": "Ustvari znova", "skip-interview": "Preskoči intervju", "update-solution": "Posodobi rešitev", "finish-edit": "Zaključi urejanje", @@ -11409,8 +11367,6 @@ "water-metering": "Merjenje porabe vode", "coffee-machine-monitoring": "Spremljanje kavnega avtomata", "fleet-geofencing": "Geografsko ograjevanje voznega parka", - "more-examples": "Več primerov", - "hide": "Skrij", "solution-info": "Podatki o rešitvi", "solution-info-with-name": "Podatki o rešitvi: {{ name }}", "status": "Stanje", @@ -11423,14 +11379,8 @@ "info": "Informacije", "main-dashboard": "Glavna nadzorna plošča", "view-as": "Prikaži kot {{ name }}", - "generated-by-calculated-field-name": "Ustvarjeno z izračunanim poljem »{{ name }}«", "estimate-wait-time": "Predviden čas čakanja je ~{{ time }}", - "analyzing-your-request": "Analiziranje vaše zahteve...", "condition": "Pogoj", - "installing": "Nameščanje rešitve...", - "step-architecture-design": "Načrtovanje arhitekture", - "step-dashboard-design": "Oblikovanje nadzorne plošče", - "step-solution-installation": "Namestitev rešitve", "step-reading-device-data": "Branje podatkov naprave…", "step-analyzing-telemetry-attributes": "Analiziranje telemetrije in atributov…", "step-selecting-widgets": "Izbiranje gradnikov za vaše podatke…", @@ -11462,11 +11412,7 @@ "step-loading-building-alarm-rules": "Gradnja pravil za alarme…", "step-loading-assembling-dashboards": "Sestavljanje nadzornih plošč…", "step-loading-preparing-states": "Pripravljanje stanj…", - "step-loading-initializing-solution": "Inicializacija rešitve…", - "ai-credits": "Krediti AI", - "ai-credits-update": "Nadgradi paket", - "ai-credits-usage": "Krediti AI: porabljeno {{ used }} od {{ max }}", - "ai-credits-description": "Ta mesec ste porabili {{ used }} od svojih {{ max }} kreditov AI. Omejitev se ponastavi {{ date }}. Če želite povečati količino kreditov AI, se obrnite na svojega sistemskega administratorja." + "step-loading-initializing-solution": "Inicializacija rešitve…" }, "widgets": { "mobile-app-qr-code": { @@ -13810,11 +13756,6 @@ "disk-warning-text": "Na disku primanjkuje prostora. Da preprečite izgubo podatkov, sprostite ali razširite prostor na disku.", "disk-critical-text": "Prostora na disku je kritično malo. Da preprečite izgubo podatkov, sprostite ali razširite prostor na disku." }, - "cluster-info": { - "service-id": "ID storitve", - "service-type": "Vrsta storitve", - "no-data": "Ni podatkov" - }, "transport-messages": { "title": "Transportna sporočila", "info": "Vsa sporočila, prejeta iz naprav" @@ -13853,41 +13794,9 @@ "no-last-viewed-dashboards": "Ogledanih nadzornih plošč še ni" }, "configured-features": { - "title": "Konfigurirane funkcije", - "info": "Stanje funkcij, ki zahtevajo konfiguracijo", - "white-labeling-feature": "Prilagajanje znamke", - "email-feature": "E-pošta", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2.0", - "2fa-feature": "2FA", "feature-configured": "Funkcija je konfigurirana.\nKliknite za nastavitev", "feature-not-configured": "Funkcija ni konfigurirana.\nKliknite za nastavitev" }, - "version-info": { - "title": "Različica", - "contact-us": "Stik z nami", - "current-version": "Trenutna različica", - "current": "Trenutna", - "available-version": "Razpoložljiva različica", - "available": "Razpoložljiva", - "upgrade": "Nadgradi", - "version-is-up-to-date": "Različica je posodobljena" - }, - "license-info": { - "title": "Podatki o licenci", - "view-all": "Prikaži vse", - "license-portal": "Portal za licence", - "devices-info": "{count} / { max, plural, =0 {∞ naprav} one {# naprava} two {# napravi} few {# naprave} other {# naprav} }", - "assets-info": "{count} / { max, plural, =0 {∞ sredstev} one {# sredstvo} two {# sredstvi} few {# sredstva} other {# sredstev} }", - "edges-info": "{count} / { max, plural, =0 {∞ instanc Edge} one {# instanca Edge} two {# instanci Edge} few {# instance Edge} other {# instanc Edge} }", - "dashboards-info": "{count} / { max, plural, =0 {∞ nadzornih plošč} one {# nadzorna plošča} two {# nadzorni plošči} few {# nadzorne plošče} other {# nadzornih plošč} }", - "integrations-info": "{count} / { max, plural, =0 {∞ integracij} one {# integracija} two {# integraciji} few {# integracije} other {# integracij} }", - "community-support": "Podpora skupnosti", - "white-labeling": "Prilagajanje znamke", - "unlimited-datapoints-and-messages": "Neomejeno število podatkovnih točk in sporočil", - "unlimited-api-calls": "Neomejeno število klicev API" - }, "usage-info": { "title": "Uporaba", "entities": "Entitete", diff --git a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json index e9337b2a7f..e0c325cca4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json +++ b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Yapay zeka ile yapılandır", - "follow-up-prompt-placeholder": "Yanıtla...", - "sub-title": "Cihazlarınızı, panolarınızı, hesaplanmış alanlarınızı, alarm kurallarınızı ve bildirimlerinizi kurmanıza ve yönetmenize yardımcı olabilirim — ne istediğinizi açıklamanız yeterli, gerisini ben hallederim.", "new-chat": "Yeni sohbet", - "no-chats": "Henüz sohbet yok", "today": "Bugün", "yesterday": "Dün", "last-7-days": "Son 7 gün", @@ -703,20 +700,12 @@ "delete-chat-title": "'{{name}}' sohbetini silmek istediğinizden emin misiniz?", "delete-chat-text": "Tüm sohbet mesajları kaybolacak", "delete-chat-confirm": "Evet, sil", - "action-approval-required": "İşlem onayı gerekli", "approve": "Onayla", - "approve-all": "Sonraki tüm eylemleri onayla", "deny": "Reddet", - "processing": "İşleniyor...", "approved": "Tamamlandı", - "denied": "Reddedildi", "error": "Başarısız", "thinking": "Düşünüyor...", - "connection-lost": "Yapay zeka asistanı ile bağlantı kesildi. Yeniden bağlanılıyor...", - "reconnect-failed": "Yapay zeka asistanına yeniden bağlanılamadı. Yanıtını görmek için sohbeti yeniden açın.", - "rename-chat-title": "Bu sohbeti yeniden adlandır", - "export-chat": "Sohbeti dışa aktar", - "main-title": "Merhaba! Ben yapay zeka asistanınızım" + "export-chat": "Sohbeti dışa aktar" }, "alarm": { "alarm": "Alarm", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Hesap kimlik bilgileri dosyanızı sürükleyip bırakın" }, "solution-creator": { - "ai-solution-creator": "Yapay zeka çözüm oluşturucu", "describe-solution-you-want": "Oluşturmak istediğiniz çözümü açıklayın", - "enter-your-prompt": "İsteminizi girin", "target": "Hedef", "install-solution": "Kur", - "solution-overview": "Çözüm özeti: {{ name }}", - "dashboards-overview": "Panolara genel bakış: {{ name }}", - "entity-profile": "Öğe profili", - "entity-profiles": "Öğe profilleri", - "name": "Ad", - "iam": "IAM", - "iam-full": "Kimlik ve erişim yönetimi", - "table-view": "Tablo", - "schema-view": "Şema", - "iam-info": "IAM bilgisi", "operation": { "C": "Oluştur", "R": "Oku", "U": "Güncelle", "D": "Sil" }, - "alarm-info": "Alarm bilgisi", "description": "Açıklama", - "data": "Veri", - "entity-info": "Öğe bilgisi", - "calculated-field-info": "Hesaplanmış alan bilgisi", - "field-type": "Alan türü", - "scope": "Kapsam", "delete-alarm-title": "Önerilen bu alarm silinsin mi?", "delete-alarm-text": "Açıklamanıza göre önerilen bu alarm, önerilen çözüme eklenmeyecek.
Alarmları daha sonra istediğiniz zaman manuel olarak düzenleyebilir veya yeniden oluşturabilirsiniz. Bu işlem geri alınamaz.", - "basic-mode": "Temel", - "advanced-mode": "Gelişmiş", "create-solution": "Çözüm oluştur", "go-dashboard-manager": "Sonraki: Pano tasarımı", - "success-generate-title": "Çözüm hazır!", - "success-generate-sub-title": "Aşağıdaki düğmeye tıklayarak çözümü hesabınıza kurabilirsiniz", - "success-generate-install-title": "Çözüm kuruldu!", - "success-generate-install-sub-title": "Çözümü düzenlemek için lütfen önce mevcut örneği kaldırın", - "main-title": "Merhaba! Ben yapay zeka asistanınızım", - "sub-title": "Gereksinimlerinizi tamamen işlevsel bir IoT çözümüne dönüştürmenize yardımcı olurum.\nNe yapmak istediğinizi açıklamanız yeterli, gerisini ben hallederim.", - "solutions": "Çözümler", "new-solution": "Yeni çözüm", "uninstall-solution": "Kaldır", "uninstall-solution-dialog-title": "‘{{ name }}’ adlı çözümü kaldırmak istediğinizden emin misiniz?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "Tüm verileriniz kaybolacak", "delete-solution-confirm": "Evet, sil", "copy-solution": "Çözümü kopyala", - "expand-sidebar": "Kenar çubuğunu genişlet", - "collapse-sidebar": "Kenar çubuğunu daralt", "solution-id": "Çözüm kimliği", "solution-id-required": "Çözüm kimliği gereklidir.", - "rename-solution-title": "Bu çözümü yeniden adlandır", - "generate-again": "Yeniden oluştur", "skip-interview": "Görüşmeyi atla", "update-solution": "Çözümü güncelle", "finish-edit": "Düzenlemeyi bitir", @@ -11300,8 +11258,6 @@ "water-metering": "Su sayacı ölçümü", "coffee-machine-monitoring": "Kahve makinesi izleme", "fleet-geofencing": "Filo coğrafi çitleme", - "more-examples": "Daha fazla örnek", - "hide": "Gizle", "solution-info": "Çözüm bilgisi", "solution-info-with-name": "Çözüm bilgisi: {{ name }}", "status": "Durum", @@ -11314,14 +11270,8 @@ "info": "Bilgi", "main-dashboard": "Ana pano", "view-as": "{{ name }} olarak görüntüle", - "generated-by-calculated-field-name": "‘{{ name }}’ hesaplanmış alanı tarafından oluşturuldu", "estimate-wait-time": "Tahmini bekleme süresi: ~{{ time }}", - "analyzing-your-request": "İsteğiniz analiz ediliyor...", "condition": "Koşul", - "installing": "Çözüm kuruluyor...", - "step-architecture-design": "Mimari tasarım", - "step-dashboard-design": "Pano tasarımı", - "step-solution-installation": "Çözüm kurulumu", "step-reading-device-data": "Cihaz verileri okunuyor…", "step-analyzing-telemetry-attributes": "Telemetri ve öznitelikler analiz ediliyor…", "step-selecting-widgets": "Verileriniz için widget'lar seçiliyor…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarm kuralları oluşturuluyor…", "step-loading-assembling-dashboards": "Panolar oluşturuluyor…", "step-loading-preparing-states": "Durumlar hazırlanıyor…", - "step-loading-initializing-solution": "Çözüm başlatılıyor…", - "ai-credits": "Yapay zeka kredileri", - "ai-credits-update": "Planı güncelle", - "ai-credits-usage": "Yapay zeka kredileri: {{ used }} / {{ max }} kullanıldı", - "ai-credits-description": "Bu ay toplam {{ max }} yapay zeka kredinizden {{ used }} tanesini kullandınız. Limit {{ date }} tarihinde sıfırlanır. Yapay zeka kredisi kotanızı artırmak için lütfen sistem yöneticinize başvurun." + "step-loading-initializing-solution": "Çözüm başlatılıyor…" }, "markdown": { "edit": "Düzenle", @@ -13783,11 +13729,6 @@ "disk-warning-text": "Disk alanı azalıyor. Veri kaybını önlemek için disk alanını boşaltın veya genişletin.", "disk-critical-text": "Disk alanı kritik düzeyde düşük. Veri kaybını önlemek için disk alanını boşaltın veya genişletin." }, - "cluster-info": { - "service-id": "Servis kimliği", - "service-type": "Servis türü", - "no-data": "Veri yok" - }, "transport-messages": { "title": "Taşıma mesajları", "info": "Cihazlardan gelen tüm mesajlar" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "Henüz son görüntülenen pano yok" }, "configured-features": { - "title": "Yapılandırılmış özellikler", - "info": "Yapılandırma gerektiren özelliklerin durumu", - "white-labeling-feature": "White labeling", - "email-feature": "E-posta", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Özellik yapılandırıldı.\nAyarlamak için tıklayın", "feature-not-configured": "Özellik yapılandırılmadı.\nKurulum için tıklayın" }, - "version-info": { - "title": "Sürüm", - "contact-us": "Bize ulaşın", - "current-version": "Mevcut sürüm", - "current": "Mevcut", - "available-version": "Kullanılabilir sürüm", - "available": "Kullanılabilir", - "upgrade": "Yükselt", - "version-is-up-to-date": "Sürüm güncel" - }, - "license-info": { - "title": "Lisans bilgisi", - "view-all": "Tümünü görüntüle", - "license-portal": "Lisans portalı", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Cihaz", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Varlık", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Pano", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Entegrasyon", - "community-support": "Topluluk desteği", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Sınırsız veri noktası ve mesaj", - "unlimited-api-calls": "Sınırsız API çağrısı" - }, "usage-info": { "title": "Kullanım", "entities": "Öğeler", diff --git a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json index c28f6da6fe..851397c032 100644 --- a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json +++ b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Налаштувати за допомогою ШІ", - "follow-up-prompt-placeholder": "Відповісти...", - "sub-title": "Я можу допомогти вам налаштувати ваші пристрої, дашборди, обчислювані поля, правила тривог і сповіщення та керувати ними — просто опишіть, що вам потрібно, а решту я зроблю сам.", "new-chat": "Новий чат", - "no-chats": "Поки що немає чатів", "today": "Сьогодні", "yesterday": "Вчора", "last-7-days": "Останні 7 днів", @@ -703,18 +700,12 @@ "delete-chat-title": "Ви впевнені, що хочете видалити '{{name}}'?", "delete-chat-text": "Усі повідомлення чату буде втрачено", "delete-chat-confirm": "Так, видалити", - "action-approval-required": "Потрібне схвалення дії", "approve": "Схвалити", - "approve-all": "Схвалити всі подальші дії", "deny": "Відхилити", - "processing": "Обробка...", "approved": "Готово", - "denied": "Відхилено", "error": "Не вдалося", "thinking": "Думаю...", - "rename-chat-title": "Перейменувати цей чат", - "export-chat": "Експортувати чат", - "main-title": "Привіт! Я ваш ШІ-асистент" + "export-chat": "Експортувати чат" }, "alarm": { "alarm": "Тривога", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Перетягніть і відпустіть файл облікових даних вашого облікового запису" }, "solution-creator": { - "ai-solution-creator": "Конструктор рішень на основі ШІ", "describe-solution-you-want": "Опишіть рішення, яке ви хочете створити", - "enter-your-prompt": "Введіть свій запит", "target": "Ціль", "install-solution": "Встановити", - "solution-overview": "Огляд рішення: {{ name }}", - "dashboards-overview": "Огляд дашбордів: {{ name }}", - "entity-profile": "Профіль сутності", - "entity-profiles": "Профілі сутностей", - "name": "Назва", - "iam": "IAM", - "iam-full": "Керування ідентифікацією та доступом", - "table-view": "Таблиця", - "schema-view": "Схема", - "iam-info": "Інформація про IAM", "operation": { "C": "Створити", "R": "Читати", "U": "Змінити", "D": "Видалити" }, - "alarm-info": "Інформація про тривогу", "description": "Опис", - "data": "Дані", - "entity-info": "Інформація про сутність", - "calculated-field-info": "Інформація про обчислюване поле", - "field-type": "Тип поля", - "scope": "Область", "delete-alarm-title": "Видалити цю запропоновану тривогу?", "delete-alarm-text": "Ця тривога, запропонована на основі вашого опису, не буде додана до запропонованої збірки рішення.
Ви завжди можете відредагувати або повторно створити тривоги вручну пізніше. Цю дію неможливо скасувати.", - "basic-mode": "Базовий", - "advanced-mode": "Розширений", "create-solution": "Створити рішення", "go-dashboard-manager": "Далі: дизайн дашборду", - "success-generate-title": "Рішення готове!", - "success-generate-sub-title": "Ви можете встановити це у своєму акаунті, натиснувши кнопку нижче", - "success-generate-install-title": "Рішення встановлено!", - "success-generate-install-sub-title": "Щоб редагувати рішення, спочатку видаліть наявний екземпляр", - "main-title": "Привіт! Я ваш ШІ-асистент", - "sub-title": "Я допоможу вам перетворити ваші вимоги на повністю функціональне IoT-рішення.\nПросто опишіть, чого ви хочете досягти, а решту я візьму на себе.", - "solutions": "Рішення", "new-solution": "Нове рішення", "uninstall-solution": "Деінсталювати", "uninstall-solution-dialog-title": "Ви впевнені, що хочете деінсталювати «{{ name }}»?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Усі ваші дані буде втрачено", "delete-solution-confirm": "Так, видалити", "copy-solution": "Копіювати рішення", - "expand-sidebar": "Розгорнути бічну панель", - "collapse-sidebar": "Згорнути бічну панель", "solution-id": "Ідентифікатор рішення", "solution-id-required": "Потрібно вказати ідентифікатор рішення", - "rename-solution-title": "Перейменувати це рішення", - "generate-again": "Згенерувати ще раз", "skip-interview": "Пропустити опитування", "update-solution": "Оновити рішення", "finish-edit": "Завершити редагування", @@ -11298,8 +11258,6 @@ "water-metering": "Облік водоспоживання", "coffee-machine-monitoring": "Моніторинг кавомашин", "fleet-geofencing": "Геозонування автопарку", - "more-examples": "Більше прикладів", - "hide": "Приховати", "solution-info": "Інформація про рішення", "solution-info-with-name": "Інформація про рішення: {{ name }}", "status": "Статус", @@ -11312,14 +11270,8 @@ "info": "Інформація", "main-dashboard": "Головний дашборд", "view-as": "Переглянути як {{ name }}", - "generated-by-calculated-field-name": "Згенеровано обчислюваним полем «{{ name }}»", "estimate-wait-time": "Орієнтовний час очікування: ~{{ time }}", - "analyzing-your-request": "Аналізуємо ваш запит...", "condition": "Умова", - "installing": "Встановлення рішення...", - "step-architecture-design": "Проєктування архітектури", - "step-dashboard-design": "Проєктування дашборду", - "step-solution-installation": "Встановлення рішення", "step-reading-device-data": "Читання даних пристрою…", "step-analyzing-telemetry-attributes": "Аналіз телеметрії та атрибутів…", "step-selecting-widgets": "Підбір віджетів для ваших даних…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Створення правил тривог…", "step-loading-assembling-dashboards": "Складання дашбордів…", "step-loading-preparing-states": "Підготовка станів…", - "step-loading-initializing-solution": "Ініціалізація рішення…", - "ai-credits": "Кредити ШІ", - "ai-credits-update": "Зберегти зміни", - "ai-credits-usage": "Кредити ШІ: використано {{ used }} з {{ max }}", - "ai-credits-description": "Ви використали {{ used }} з {{ max }} кредитів ШІ цього місяця. Ліміт скидається {{ date }}. Щоб збільшити ліміт кредитів ШІ, зверніться до системного адміністратора." + "step-loading-initializing-solution": "Ініціалізація рішення…" }, "markdown": { "edit": "Редагувати", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Мало місця на диску. Щоб уникнути втрати даних, звільніть або розширте дисковий простір.", "disk-critical-text": "Критично мало місця на диску. Щоб уникнути втрати даних, звільніть або розширте дисковий простір." }, - "cluster-info": { - "service-id": "Id сервісу", - "service-type": "Тип сервісу", - "no-data": "Немає даних" - }, "transport-messages": { "title": "Транспортні повідомлення", "info": "Усі повідомлення, що надійшли від пристроїв" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Поки немає нещодавно переглянутих дашбордів" }, "configured-features": { - "title": "Налаштовані можливості", - "info": "Статус можливостей, що потребують налаштування", - "white-labeling-feature": "Брендування", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Функцію налаштовано.\nНатисніть, щоб налаштувати", "feature-not-configured": "Функцію не налаштовано.\nНатисніть, щоб налаштувати" }, - "version-info": { - "title": "Версія", - "contact-us": "Зв’язатися з нами", - "current-version": "Поточна версія", - "current": "Поточна", - "available-version": "Доступна версія", - "available": "Доступна", - "upgrade": "Оновити версію", - "version-is-up-to-date": "Версія актуальна" - }, - "license-info": { - "title": "Інформація про ліцензію", - "view-all": "Переглянути все", - "license-portal": "Портал ліцензій", - "devices-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Пристрої", - "assets-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Активи", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Дашборди", - "integrations-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Інтеграції", - "community-support": "Підтримка спільноти", - "white-labeling": "Брендування", - "unlimited-datapoints-and-messages": "Необмежені точки даних і повідомлення", - "unlimited-api-calls": "Необмежені виклики API" - }, "usage-info": { "title": "Використання", "entities": "Сутності", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json index 74fedf0f9a..6af47c0059 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "使用 AI 配置", - "follow-up-prompt-placeholder": "回复...", - "sub-title": "我可以帮助您设置和管理您的设备、仪表板、计算字段、告警规则和通知——只需描述您的需求,其余的交给我。", "new-chat": "新对话", - "no-chats": "暂无对话", "today": "今天", "yesterday": "昨天", "last-7-days": "最近 7 天", @@ -703,20 +700,12 @@ "delete-chat-title": "确定要删除 '{{name}}' 吗?", "delete-chat-text": "所有对话消息将丢失", "delete-chat-confirm": "是,删除", - "action-approval-required": "操作需要审批", "approve": "批准", - "approve-all": "批准后续所有操作", "deny": "拒绝", - "processing": "处理中...", "approved": "完成", - "denied": "已拒绝", "error": "失败", "thinking": "思考中...", - "connection-lost": "与 AI 助手的连接已断开。正在重新连接...", - "reconnect-failed": "无法重新连接到 AI 助手。请重新打开对话以查看其回复。", - "rename-chat-title": "重命名此对话", - "export-chat": "导出对话", - "main-title": "您好!我是您的 AI 助手" + "export-chat": "导出对话" }, "alarm": { "alarm": "告警", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "拖放您的账户凭据文件" }, "solution-creator": { - "ai-solution-creator": "AI 解决方案创建器", "describe-solution-you-want": "描述您要创建的解决方案", - "enter-your-prompt": "输入提示词", "target": "目标", "install-solution": "安装", - "solution-overview": "解决方案概览:{{ name }}", - "dashboards-overview": "仪表板概览:{{ name }}", - "entity-profile": "实体配置", - "entity-profiles": "实体配置", - "name": "名称", - "iam": "IAM", - "iam-full": "身份和访问管理", - "table-view": "表格", - "schema-view": "架构", - "iam-info": "IAM 信息", "operation": { "C": "创建", "R": "读取", "U": "更新", "D": "删除" }, - "alarm-info": "告警信息", "description": "描述", - "data": "数据", - "entity-info": "实体信息", - "calculated-field-info": "计算字段信息", - "field-type": "字段类型", - "scope": "范围", "delete-alarm-title": "删除此建议告警?", "delete-alarm-text": "此告警是根据您的描述建议的,删除后将不会添加到拟构建的解决方案中。
您以后随时可以手动编辑或重新创建告警。此操作无法撤销。", - "basic-mode": "基础", - "advanced-mode": "高级", "create-solution": "创建解决方案", "go-dashboard-manager": "下一步:仪表板设计", - "success-generate-title": "解决方案已就绪!", - "success-generate-sub-title": "点击下方按钮,即可将其安装到您的账户", - "success-generate-install-title": "解决方案已安装!", - "success-generate-install-sub-title": "如需编辑该解决方案,请先卸载现有实例", - "main-title": "您好!我是您的 AI 助手", - "sub-title": "我可以帮助您将需求转化为功能完备的物联网解决方案。\n只需描述您想实现的目标,其余的交给我。", - "solutions": "解决方案", "new-solution": "新建解决方案", "uninstall-solution": "卸载", "uninstall-solution-dialog-title": "确定要卸载“{{ name }}”吗?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "您的所有数据都将丢失。", "delete-solution-confirm": "是,删除", "copy-solution": "复制解决方案", - "expand-sidebar": "展开侧边栏", - "collapse-sidebar": "收起侧边栏", "solution-id": "解决方案 ID", "solution-id-required": "解决方案 ID 为必填项。", - "rename-solution-title": "重命名此解决方案", - "generate-again": "重新生成", "skip-interview": "跳过问答", "update-solution": "更新解决方案", "finish-edit": "完成编辑", @@ -11300,8 +11258,6 @@ "water-metering": "水表计量", "coffee-machine-monitoring": "咖啡机监控", "fleet-geofencing": "车队地理围栏", - "more-examples": "更多示例", - "hide": "隐藏", "solution-info": "解决方案信息", "solution-info-with-name": "解决方案信息:{{ name }}", "status": "状态", @@ -11314,14 +11270,8 @@ "info": "信息", "main-dashboard": "主仪表板", "view-as": "以 {{ name }} 身份查看", - "generated-by-calculated-field-name": "由计算字段“{{ name }}”生成", "estimate-wait-time": "预计等待时间约为 {{ time }}", - "analyzing-your-request": "正在分析您的请求...", "condition": "条件", - "installing": "正在安装解决方案...", - "step-architecture-design": "架构设计", - "step-dashboard-design": "仪表板设计", - "step-solution-installation": "解决方案安装", "step-reading-device-data": "正在读取设备数据…", "step-analyzing-telemetry-attributes": "正在分析遥测和属性…", "step-selecting-widgets": "正在为您的数据选择部件…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "正在构建告警规则…", "step-loading-assembling-dashboards": "正在组装仪表板…", "step-loading-preparing-states": "正在准备状态…", - "step-loading-initializing-solution": "正在初始化解决方案…", - "ai-credits": "AI 额度", - "ai-credits-update": "更改套餐", - "ai-credits-usage": "AI 额度:已使用 {{ used }}/{{ max }}", - "ai-credits-description": "本月您已使用 AI 额度 {{ used }}/{{ max }}。额度将于 {{ date }} 重置。如需提高 AI 额度,请联系系统管理员。" + "step-loading-initializing-solution": "正在初始化解决方案…" }, "markdown": { "edit": "编辑", @@ -13783,11 +13729,6 @@ "disk-warning-text": "磁盘空间不足。为避免数据丢失,请释放或扩展磁盘空间。", "disk-critical-text": "磁盘空间严重不足。为避免数据丢失,请释放或扩展磁盘空间。" }, - "cluster-info": { - "service-id": "服务 ID", - "service-type": "服务类型", - "no-data": "暂无数据" - }, "transport-messages": { "title": "传输消息", "info": "来自设备的所有消息" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "暂无最近查看的仪表板" }, "configured-features": { - "title": "已配置功能", - "info": "需要配置的功能状态", - "white-labeling-feature": "白标", - "email-feature": "邮件", - "sms-feature": "短信", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "双因素认证", "feature-configured": "功能已配置。\n点击进行设置", "feature-not-configured": "功能未配置。\n点击进行设置" }, - "version-info": { - "title": "版本", - "contact-us": "联系我们", - "current-version": "当前版本", - "current": "当前", - "available-version": "可用版本", - "available": "可用", - "upgrade": "升级", - "version-is-up-to-date": "版本已是最新" - }, - "license-info": { - "title": "许可证信息", - "view-all": "查看全部", - "license-portal": "许可证门户", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } 设备", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } 资产", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } 仪表板", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } 集成", - "community-support": "社区支持", - "white-labeling": "白标", - "unlimited-datapoints-and-messages": "无限数据点和消息", - "unlimited-api-calls": "无限 API 调用" - }, "usage-info": { "title": "使用情况", "entities": "实体", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json index 84e663026d..65f90b1de2 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json @@ -7532,11 +7532,6 @@ "disk-warning-text": "磁碟空間不足。為避免資料遺失,請釋放或擴充磁碟空間。", "disk-critical-text": "磁碟空間嚴重不足。為避免資料遺失,請釋放或擴充磁碟空間。" }, - "cluster-info": { - "service-id": "服務識別碼", - "service-type": "服務類型", - "no-data": "尚無資料" - }, "transport-messages": { "title": "傳輸訊息", "info": "來自裝置的所有訊息" @@ -7575,26 +7570,8 @@ "no-last-viewed-dashboards": "尚無最近檢視的儀表板" }, "configured-features": { - "title": "已設定功能", - "info": "需要設定的功能狀態", - "email-feature": "電子郵件", - "sms-feature": "簡訊", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "雙因素驗證", "feature-configured": "功能已設定。\n點選進行設定", - "feature-not-configured": "功能未設定。\n點選進行設定", - "white-labeling-feature": "白標" - }, - "version-info": { - "title": "版本", - "contact-us": "聯絡我們", - "current-version": "目前版本", - "current": "目前", - "available-version": "可用版本", - "available": "可用", - "upgrade": "升級", - "version-is-up-to-date": "版本已是最新" + "feature-not-configured": "功能未設定。\n點選進行設定" }, "usage-info": { "title": "使用情況", @@ -7774,20 +7751,6 @@ "align-top": "靠上對齊", "align-middle": "垂直置中", "align-bottom": "靠下對齊" - }, - "license-info": { - "title": "授權資訊", - "view-all": "檢視全部", - "license-portal": "授權入口網站", - "devices-info": "裝置:{count} / { max, plural, =0 {∞} other {#} }", - "assets-info": "資產:{count} / { max, plural, =0 {∞} other {#} }", - "edges-info": "Edge:{count} / { max, plural, =0 {∞} other {#} }", - "dashboards-info": "儀表板:{count} / { max, plural, =0 {∞} other {#} }", - "integrations-info": "整合:{count} / { max, plural, =0 {∞} other {#} }", - "community-support": "社群支援", - "white-labeling": "白標", - "unlimited-datapoints-and-messages": "不限資料點與訊息數量", - "unlimited-api-calls": "不限 API 呼叫次數" } }, "icon": { @@ -11476,10 +11439,7 @@ }, "ai-assistant": { "configure-with-ai": "使用 AI 設定", - "follow-up-prompt-placeholder": "回覆…", - "sub-title": "我可以協助您設定及管理裝置、儀表板、計算欄位、警報規則和通知。只要描述您的需求,其餘交給我。", "new-chat": "新對話", - "no-chats": "尚無對話", "today": "今天", "yesterday": "昨天", "last-7-days": "最近 7 天", @@ -11487,20 +11447,12 @@ "delete-chat-title": "確定要刪除「{{name}}」嗎?", "delete-chat-text": "所有對話訊息都將遺失。", "delete-chat-confirm": "是,刪除", - "action-approval-required": "需要核准此操作", "approve": "核准", "deny": "拒絕", - "processing": "處理中…", "approved": "完成", - "denied": "已拒絕", "error": "失敗", "thinking": "思考中…", - "rename-chat-title": "重新命名此對話", - "main-title": "您好!我是您的 AI 助理", - "approve-all": "核准後續所有操作", - "export-chat": "匯出對話", - "connection-lost": "與 AI 助理的連線已中斷。正在重新連線…", - "reconnect-failed": "無法重新連線至 AI 助理。請重新開啟對話以查看其回覆。" + "export-chat": "匯出對話" }, "converter": { "converter": "資料轉換器", @@ -13202,47 +13154,20 @@ "generate-report-canceled": "已取消產生報表" }, "solution-creator": { - "ai-solution-creator": "AI 解決方案建立工具", "describe-solution-you-want": "描述您想建立的解決方案", - "enter-your-prompt": "輸入您的提示詞", "target": "目標", "install-solution": "安裝", - "solution-overview": "解決方案概觀:{{ name }}", - "dashboards-overview": "儀表板概觀:{{ name }}", - "entity-profile": "實體設定檔", - "entity-profiles": "實體設定檔", - "name": "名稱", - "iam": "IAM", - "iam-full": "身分識別與存取管理", - "table-view": "表格", - "schema-view": "結構圖", - "iam-info": "IAM 資訊", "operation": { "C": "建立", "R": "讀取", "U": "更新", "D": "刪除" }, - "alarm-info": "警報資訊", "description": "說明", - "data": "資料", - "entity-info": "實體資訊", - "calculated-field-info": "計算欄位資訊", - "field-type": "欄位類型", - "scope": "範圍", "delete-alarm-title": "要刪除此建議的警報嗎?", "delete-alarm-text": "此警報是依據您的描述所提出的建議,刪除後將不會納入建議的解決方案。
您隨時可以在之後手動編輯或重新建立警報。此操作無法復原。", - "basic-mode": "基本", - "advanced-mode": "進階", "create-solution": "建立解決方案", "go-dashboard-manager": "下一步:設計儀表板", - "success-generate-title": "解決方案已就緒!", - "success-generate-sub-title": "按一下下方按鈕,即可將解決方案安裝至您的帳戶", - "success-generate-install-title": "解決方案已安裝!", - "success-generate-install-sub-title": "若要編輯解決方案,請先解除安裝現有執行個體", - "main-title": "您好!我是您的 AI 助理", - "sub-title": "我可以協助您將需求轉換為功能完整的 IoT 解決方案。\n只要描述您想達成的目標,剩下的交給我處理。", - "solutions": "解決方案", "new-solution": "新解決方案", "uninstall-solution": "解除安裝", "uninstall-solution-dialog-title": "確定要解除安裝「{{ name }}」嗎?", @@ -13252,12 +13177,8 @@ "delete-solution-text": "您的所有資料都將遺失", "delete-solution-confirm": "是,刪除", "copy-solution": "複製解決方案", - "expand-sidebar": "展開側邊欄", - "collapse-sidebar": "摺疊側邊欄", "solution-id": "解決方案識別碼", "solution-id-required": "解決方案識別碼為必填項", - "rename-solution-title": "重新命名此解決方案", - "generate-again": "重新產生", "skip-interview": "略過需求訪談", "update-solution": "更新解決方案", "finish-edit": "完成編輯", @@ -13267,8 +13188,6 @@ "water-metering": "用水計量", "coffee-machine-monitoring": "咖啡機監測", "fleet-geofencing": "車隊地理圍欄", - "more-examples": "更多範例", - "hide": "隱藏", "solution-info": "解決方案資訊", "solution-info-with-name": "解決方案資訊:{{ name }}", "status": "狀態", @@ -13281,14 +13200,8 @@ "info": "資訊", "main-dashboard": "主要儀表板", "view-as": "以「{{ name }}」的身分檢視", - "generated-by-calculated-field-name": "由計算欄位「{{ name }}」產生", "estimate-wait-time": "預計等待時間約為 {{ time }}", - "analyzing-your-request": "正在分析您的請求…", "condition": "條件", - "installing": "正在安裝解決方案…", - "step-architecture-design": "架構設計", - "step-dashboard-design": "儀表板設計", - "step-solution-installation": "解決方案安裝", "step-reading-device-data": "正在讀取裝置資料…", "step-analyzing-telemetry-attributes": "正在分析遙測與屬性…", "step-selecting-widgets": "正在為您的資料選擇小工具…", @@ -13320,11 +13233,7 @@ "step-loading-building-alarm-rules": "正在建立警報規則…", "step-loading-assembling-dashboards": "正在組合儀表板…", "step-loading-preparing-states": "正在準備狀態…", - "step-loading-initializing-solution": "正在初始化解決方案…", - "ai-credits": "AI 點數", - "ai-credits-update": "更新方案", - "ai-credits-usage": "AI 點數:已使用 {{ used }},共 {{ max }}", - "ai-credits-description": "本月 AI 點數總額為 {{ max }},已使用 {{ used }}。額度將於 {{ date }} 重設。若要提高 AI 點數額度,請聯絡系統管理員。" + "step-loading-initializing-solution": "正在初始化解決方案…" }, "setup": { "activate-platform": "啟用 ThingsBoard", diff --git a/ui-ngx/src/assets/solution-creator/iot-assistant.svg b/ui-ngx/src/assets/solution-creator/iot-assistant.svg deleted file mode 100644 index 2e473adefa..0000000000 --- a/ui-ngx/src/assets/solution-creator/iot-assistant.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/ui-ngx/src/assets/solution-creator/success.svg b/ui-ngx/src/assets/solution-creator/success.svg deleted file mode 100644 index 58b757228b..0000000000 --- a/ui-ngx/src/assets/solution-creator/success.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/ui-ngx/src/scss/roboto.scss b/ui-ngx/src/scss/roboto.scss new file mode 100644 index 0000000000..48806a35f9 --- /dev/null +++ b/ui-ngx/src/scss/roboto.scss @@ -0,0 +1,275 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +// The @font-face rules of @fontsource-variable/roboto (index.css, wght-italic.css) and +// @fontsource-variable/roboto-mono (index.css, wght-italic.css), copied with the families renamed from 'Roboto Variable' +// and 'Roboto Mono Variable' to 'Roboto' and 'Roboto Mono' and the file URLs pointed at node_modules. +// After upgrading either package, copy those rules again the same way. +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-cyrillic-ext-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-cyrillic-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-greek-ext-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+1F00-1FFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-greek-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-math-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0302-0303,U+0305,U+0307-0308,U+0310,U+0312,U+0315,U+031A,U+0326-0327,U+032C,U+032F-0330,U+0332-0333,U+0338,U+033A,U+0346,U+034D,U+0391-03A1,U+03A3-03A9,U+03B1-03C9,U+03D1,U+03D5-03D6,U+03F0-03F1,U+03F4-03F5,U+2016-2017,U+2034-2038,U+203C,U+2040,U+2043,U+2047,U+2050,U+2057,U+205F,U+2070-2071,U+2074-208E,U+2090-209C,U+20D0-20DC,U+20E1,U+20E5-20EF,U+2100-2112,U+2114-2115,U+2117-2121,U+2123-214F,U+2190,U+2192,U+2194-21AE,U+21B0-21E5,U+21F1-21F2,U+21F4-2211,U+2213-2214,U+2216-22FF,U+2308-230B,U+2310,U+2319,U+231C-2321,U+2336-237A,U+237C,U+2395,U+239B-23B7,U+23D0,U+23DC-23E1,U+2474-2475,U+25AF,U+25B3,U+25B7,U+25BD,U+25C1,U+25CA,U+25CC,U+25FB,U+266D-266F,U+27C0-27FF,U+2900-2AFF,U+2B0E-2B11,U+2B30-2B4C,U+2BFE,U+3030,U+FF5B,U+FF5D,U+1D400-1D7FF,U+1EE00-1EEFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-symbols-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0001-000C,U+000E-001F,U+007F-009F,U+20DD-20E0,U+20E2-20E4,U+2150-218F,U+2190,U+2192,U+2194-2199,U+21AF,U+21E6-21F0,U+21F3,U+2218-2219,U+2299,U+22C4-22C6,U+2300-243F,U+2440-244A,U+2460-24FF,U+25A0-27BF,U+2800-28FF,U+2921-2922,U+2981,U+29BF,U+29EB,U+2B00-2BFF,U+4DC0-4DFF,U+FFF9-FFFB,U+10140-1018E,U+10190-1019C,U+101A0,U+101D0-101FD,U+102E0-102FB,U+10E60-10E7E,U+1D2C0-1D2D3,U+1D2E0-1D37F,U+1F000-1F0FF,U+1F100-1F1AD,U+1F1E6-1F1FF,U+1F30D-1F30F,U+1F315,U+1F31C,U+1F31E,U+1F320-1F32C,U+1F336,U+1F378,U+1F37D,U+1F382,U+1F393-1F39F,U+1F3A7-1F3A8,U+1F3AC-1F3AF,U+1F3C2,U+1F3C4-1F3C6,U+1F3CA-1F3CE,U+1F3D4-1F3E0,U+1F3ED,U+1F3F1-1F3F3,U+1F3F5-1F3F7,U+1F408,U+1F415,U+1F41F,U+1F426,U+1F43F,U+1F441-1F442,U+1F444,U+1F446-1F449,U+1F44C-1F44E,U+1F453,U+1F46A,U+1F47D,U+1F4A3,U+1F4B0,U+1F4B3,U+1F4B9,U+1F4BB,U+1F4BF,U+1F4C8-1F4CB,U+1F4D6,U+1F4DA,U+1F4DF,U+1F4E3-1F4E6,U+1F4EA-1F4ED,U+1F4F7,U+1F4F9-1F4FB,U+1F4FD-1F4FE,U+1F503,U+1F507-1F50B,U+1F50D,U+1F512-1F513,U+1F53E-1F54A,U+1F54F-1F5FA,U+1F610,U+1F650-1F67F,U+1F687,U+1F68D,U+1F691,U+1F694,U+1F698,U+1F6AD,U+1F6B2,U+1F6B9-1F6BA,U+1F6BC,U+1F6C6-1F6CF,U+1F6D3-1F6D7,U+1F6E0-1F6EA,U+1F6F0-1F6F3,U+1F6F7-1F6FC,U+1F700-1F7FF,U+1F800-1F80B,U+1F810-1F847,U+1F850-1F859,U+1F860-1F887,U+1F890-1F8AD,U+1F8B0-1F8BB,U+1F8C0-1F8C1,U+1F900-1F90B,U+1F93B,U+1F946,U+1F984,U+1F996,U+1F9E9,U+1FA00-1FA6F,U+1FA70-1FA7C,U+1FA80-1FA89,U+1FA8F-1FAC6,U+1FACE-1FADC,U+1FADF-1FAE9,U+1FAF0-1FAF8,U+1FB00-1FBFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-vietnamese-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-latin-ext-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; +} + +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-latin-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-cyrillic-ext-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-cyrillic-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-greek-ext-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+1F00-1FFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-greek-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-math-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0302-0303,U+0305,U+0307-0308,U+0310,U+0312,U+0315,U+031A,U+0326-0327,U+032C,U+032F-0330,U+0332-0333,U+0338,U+033A,U+0346,U+034D,U+0391-03A1,U+03A3-03A9,U+03B1-03C9,U+03D1,U+03D5-03D6,U+03F0-03F1,U+03F4-03F5,U+2016-2017,U+2034-2038,U+203C,U+2040,U+2043,U+2047,U+2050,U+2057,U+205F,U+2070-2071,U+2074-208E,U+2090-209C,U+20D0-20DC,U+20E1,U+20E5-20EF,U+2100-2112,U+2114-2115,U+2117-2121,U+2123-214F,U+2190,U+2192,U+2194-21AE,U+21B0-21E5,U+21F1-21F2,U+21F4-2211,U+2213-2214,U+2216-22FF,U+2308-230B,U+2310,U+2319,U+231C-2321,U+2336-237A,U+237C,U+2395,U+239B-23B7,U+23D0,U+23DC-23E1,U+2474-2475,U+25AF,U+25B3,U+25B7,U+25BD,U+25C1,U+25CA,U+25CC,U+25FB,U+266D-266F,U+27C0-27FF,U+2900-2AFF,U+2B0E-2B11,U+2B30-2B4C,U+2BFE,U+3030,U+FF5B,U+FF5D,U+1D400-1D7FF,U+1EE00-1EEFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-symbols-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0001-000C,U+000E-001F,U+007F-009F,U+20DD-20E0,U+20E2-20E4,U+2150-218F,U+2190,U+2192,U+2194-2199,U+21AF,U+21E6-21F0,U+21F3,U+2218-2219,U+2299,U+22C4-22C6,U+2300-243F,U+2440-244A,U+2460-24FF,U+25A0-27BF,U+2800-28FF,U+2921-2922,U+2981,U+29BF,U+29EB,U+2B00-2BFF,U+4DC0-4DFF,U+FFF9-FFFB,U+10140-1018E,U+10190-1019C,U+101A0,U+101D0-101FD,U+102E0-102FB,U+10E60-10E7E,U+1D2C0-1D2D3,U+1D2E0-1D37F,U+1F000-1F0FF,U+1F100-1F1AD,U+1F1E6-1F1FF,U+1F30D-1F30F,U+1F315,U+1F31C,U+1F31E,U+1F320-1F32C,U+1F336,U+1F378,U+1F37D,U+1F382,U+1F393-1F39F,U+1F3A7-1F3A8,U+1F3AC-1F3AF,U+1F3C2,U+1F3C4-1F3C6,U+1F3CA-1F3CE,U+1F3D4-1F3E0,U+1F3ED,U+1F3F1-1F3F3,U+1F3F5-1F3F7,U+1F408,U+1F415,U+1F41F,U+1F426,U+1F43F,U+1F441-1F442,U+1F444,U+1F446-1F449,U+1F44C-1F44E,U+1F453,U+1F46A,U+1F47D,U+1F4A3,U+1F4B0,U+1F4B3,U+1F4B9,U+1F4BB,U+1F4BF,U+1F4C8-1F4CB,U+1F4D6,U+1F4DA,U+1F4DF,U+1F4E3-1F4E6,U+1F4EA-1F4ED,U+1F4F7,U+1F4F9-1F4FB,U+1F4FD-1F4FE,U+1F503,U+1F507-1F50B,U+1F50D,U+1F512-1F513,U+1F53E-1F54A,U+1F54F-1F5FA,U+1F610,U+1F650-1F67F,U+1F687,U+1F68D,U+1F691,U+1F694,U+1F698,U+1F6AD,U+1F6B2,U+1F6B9-1F6BA,U+1F6BC,U+1F6C6-1F6CF,U+1F6D3-1F6D7,U+1F6E0-1F6EA,U+1F6F0-1F6F3,U+1F6F7-1F6FC,U+1F700-1F7FF,U+1F800-1F80B,U+1F810-1F847,U+1F850-1F859,U+1F860-1F887,U+1F890-1F8AD,U+1F8B0-1F8BB,U+1F8C0-1F8C1,U+1F900-1F90B,U+1F93B,U+1F946,U+1F984,U+1F996,U+1F9E9,U+1FA00-1FA6F,U+1FA70-1FA7C,U+1FA80-1FA89,U+1FA8F-1FAC6,U+1FACE-1FADC,U+1FADF-1FAE9,U+1FAF0-1FAF8,U+1FB00-1FBFF; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-vietnamese-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-latin-ext-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; +} + +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-display: swap; + font-weight: 100 900; + src: url('../../node_modules/@fontsource-variable/roboto/files/roboto-latin-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-cyrillic-ext-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-cyrillic-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-greek-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-vietnamese-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-latin-ext-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: normal; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-latin-wght-normal.woff2') format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-cyrillic-ext-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-cyrillic-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-greek-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-vietnamese-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-latin-ext-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; +} + +@font-face { + font-family: 'Roboto Mono'; + font-style: italic; + font-display: swap; + font-weight: 100 700; + src: url('../../node_modules/@fontsource-variable/roboto-mono/files/roboto-mono-latin-wght-italic.woff2') format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} diff --git a/ui-ngx/src/styles.scss b/ui-ngx/src/styles.scss index 425c7ee10b..29336612ca 100644 --- a/ui-ngx/src/styles.scss +++ b/ui-ngx/src/styles.scss @@ -2,8 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 /* You can add global styles to this file, and also import other style files */ -@import 'typeface-roboto/index.css'; -@import 'typeface-roboto-mono/index.css'; +@import './scss/roboto'; @import 'font-awesome/css/font-awesome.min.css'; @import './scss/constants'; @import './scss/animations'; @@ -343,117 +342,6 @@ tb-entities-table.white-background { } } -.tb-popover.tb-ai-tip { - $tip-bg: #1f2a31; - - .tb-popover-inner { - border-radius: 8px; - background-color: $tip-bg; - box-shadow: 0 6px 20px rgba(16, 24, 40, 0.22); - } - - .tb-popover-inner-content { - padding: 0; - overflow: visible; - } - - &[class*='tb-popover-placement-top'] > .tb-popover-content > .tb-popover-arrow { - border-right-color: $tip-bg; - border-bottom-color: $tip-bg; - box-shadow: none; - } - - &[class*='tb-popover-placement-bottom'] > .tb-popover-content > .tb-popover-arrow { - border-top-color: $tip-bg; - border-left-color: $tip-bg; - box-shadow: none; - } - - .tb-ai-tip-body { - box-sizing: border-box; - width: max-content; - max-width: min(248px, calc(100vw - 16px)); - padding: 9px 12px 10px; - color: #d5dde2; - font: 400 12px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; - letter-spacing: .1px; - - b { - display: block; - margin: 0; - font-size: 13px; - line-height: 18px; - font-weight: 500; - color: #fff; - } - - p { - margin: 0; - font: inherit; - letter-spacing: inherit; - } - - p + p { - margin-top: 3px; - } - - .tip-sub { - color: #9fadb7; - } - - .tip-head { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 16px; - margin-bottom: 3px; - } - - .tip-keyrow { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - min-height: 22px; - } - - .tip-caps { - display: inline-flex; - gap: 3px; - } - - kbd { - min-width: 16px; - height: 17px; - box-sizing: border-box; - padding: 0 4px; - border: 0; - border-radius: 4px; - background: rgba(255, 255, 255, 0.14); - color: #fff; - font: 500 10.5px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; - text-align: center; - } - - &.tip-keys { - min-width: 208px; - - .tip-head { - margin-bottom: 2px; - } - } - - &.tip-mini { - padding: 5px 8px 6px; - - .tip-keyrow { - gap: 10px; - min-height: 18px; - } - } - } -} - .tb-autocomplete { .mat-mdc-option { border-bottom: 1px solid #eee; diff --git a/ui-ngx/src/theme/_app-theme-palette.scss b/ui-ngx/src/theme/_app-theme-palette.scss new file mode 100644 index 0000000000..7e3383e16a --- /dev/null +++ b/ui-ngx/src/theme/_app-theme-palette.scss @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '@angular/material' as mat; +@use '@angular/material/core/tokens/m2-utils'; +@import './theme-constants'; + +$tb-primary: mat.m2-define-palette($mat-tb-primary); +$tb-accent: mat.m2-define-palette($mat-tb-accent); + +$tb-mat-theme: mat.m2-define-light-theme(( + color: ( + primary: $tb-primary, + accent: $tb-accent + ), + typography: mat.m2-define-typography-config( + $button: mat.m2-define-typography-level(14px, 36px, 500, $letter-spacing: 0.03125em) + ), + density: 0 +)); + +$tb-theme-system: m2-utils.get-system($tb-mat-theme); +$tb-theme-system: map_merge($tb-theme-system, ( background: map_get(mat.$m2-grey-palette, 200) )); +$tb-theme: map_merge($tb-mat-theme, (_mat-system: $tb-theme-system)); diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss new file mode 100644 index 0000000000..c64c46991e --- /dev/null +++ b/ui-ngx/src/theme/ai-theme.scss @@ -0,0 +1,6970 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The AI experience's styles (Uplink): its design tokens on :root, then the global rules of the AI components. +// Tokens: --ai-* the AI's colour and light, --chat-* type, space and touch, --entity-* entity types, +// --hl-* / --tb-code-* the code palette, --k-* the chat's greys and strokes. Rules use a token where one exists; +// one-off shades of the design (mostly on dark surfaces) stay literal. +// [data-ai] gives AI surfaces the AI's teal instead of the white-labeled primary palette, as the design specifies. + +:root { + --tb-ink-76: rgba(0, 0, 0, 0.76); + --tb-ink-60: rgba(0, 0, 0, 0.6); + --tb-ink-54: rgba(0, 0, 0, 0.54); + --tb-ink-38: rgba(0, 0, 0, 0.38); + --tb-ink-12: rgba(0, 0, 0, 0.12); + --tb-text-secondary: rgba(0, 0, 0, 0.6); + --tb-text-muted: rgba(0, 0, 0, 0.56); + --tb-line-soft: rgba(0, 0, 0, 0.05); + --tb-line: rgba(0, 0, 0, 0.12); + --tb-surface: #ffffff; + + --tb-caution-text: #955400; + --tb-ok: #198038; + --tb-ok-tint: rgba(25, 128, 56, 0.08); + --tb-ok-text: #16702f; + + --tb-sev-critical: #D12730; + --tb-sev-major: #F35E09; + --tb-sev-minor: #B47604; + --tb-sev-warning: var(--tb-sev-minor); + --tb-sev-indeterminate: rgba(0, 0, 0, 0.54); + --tb-sev-major-text: #B04306; + --tb-sev-minor-text: #8A5A02; + --tb-sev-warning-text: #7D7003; + + --tb-soft-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); + --tb-tile-radius: 10px; + + --tb-font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; + --tb-mono: "Roboto Mono", SFMono-Regular, Menlo, monospace; + + --ai-hue: 180; + --ai-light-mint: oklch(0.87 0.06 calc(var(--ai-hue) - 20)); + --ai-light-teal: oklch(0.86 0.08 calc(var(--ai-hue) - 5)); + --ai-mark-fill: + radial-gradient(80% 80% at 16% 10%, oklch(0.995 0.008 calc(var(--ai-hue) + 5) / 0.7), transparent 62%), + radial-gradient(55% 55% at 0% 100%, color-mix(in oklab, var(--ai-light-mint) 45%, transparent), transparent 70%), + linear-gradient(135deg in oklab, oklch(0.91 0.055 calc(var(--ai-hue) - 8)) 0%, oklch(0.935 0.045 calc(var(--ai-hue) + 25)) 38%, oklch(0.915 0.04 295) 70%, oklch(0.94 0.028 70) 100%); + --ai-mark-edge: + inset -1px -1px 1px 0 oklch(1 0 0 / 0.75), + inset 0 0 0 1px oklch(0.62 0.08 var(--ai-hue) / 0.14); + --ai-mark-ink: var(--tb-ink); + --ai-mark-ink-a: oklch(0.46 0.065 calc(var(--ai-hue) - 5)); + --ai-mark-ink-b: oklch(0.27 0.025 calc(var(--ai-hue) + 25)); + --ai-mark-ink-c: oklch(0.19 0.015 295); + --ai-mark-ink-fill: linear-gradient(135deg in oklab, var(--ai-mark-ink-a) 0%, var(--ai-mark-ink-b) 50%, var(--ai-mark-ink-c) 100%); + --ai-light-aqua: oklch(0.88 0.07 calc(var(--ai-hue) + 25)); + --ai-light-lilac: oklch(0.84 0.06 295); + --ai-light-peach: oklch(0.88 0.06 45); + --ai-light-amber: oklch(0.90 0.06 80); + --ai-light-anchor: oklch(0.80 0.11 calc(var(--ai-hue) + 2)); + --ai-light-paper: oklch(0.985 0.005 calc(var(--ai-hue) + 5)); + --ai-w-teal: 90%; + --ai-w-aqua: 80%; + --ai-w-mint: 71%; + --ai-w-lilac: 55%; + --ai-w-peach: 69%; + --ai-w-amber: 55%; + --ai-light-stops: var(--ai-light-teal), var(--ai-light-aqua), var(--ai-light-lilac), var(--ai-light-peach), var(--ai-light-amber), var(--ai-light-mint), var(--ai-light-teal); + --ai-glow: conic-gradient(in oklab, var(--ai-light-stops)); + --ai-field-tile: + radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) var(--ai-w-teal), transparent), transparent 70%), + radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) var(--ai-w-aqua), transparent), transparent 70%), + radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) var(--ai-w-mint), transparent), transparent 70%), + radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) var(--ai-w-lilac), transparent), transparent 72%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) var(--ai-w-peach), transparent), transparent 70%), + radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) var(--ai-w-amber), transparent), transparent 70%), + var(--ai-light-paper); + --ai-field-wash: + radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) calc(var(--ai-w-teal) * .87), transparent), transparent 70%), + radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) calc(var(--ai-w-aqua) * .87), transparent), transparent 70%), + radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) calc(var(--ai-w-mint) * .87), transparent), transparent 70%), + radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) calc(var(--ai-w-lilac) * .87), transparent), transparent 72%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .87), transparent), transparent 70%), + radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .87), transparent), transparent 70%), + var(--ai-light-paper); + + --chat-text: 16px; + --chat-text-lh: 24px; + --chat-head: 16px; + --chat-head-lh: 24px; + --chat-line: 14px; + --chat-line-lh: 20px; + --chat-chip: 14px; + --chat-chip-lh: 18px; + --chat-chip-pad: 1px; + --chat-chip-mono: 14px; + --chat-meta: 12px; + --chat-meta-lh: 16px; + --chat-caption: 12px; + --chat-caption-lh: 16px; + --chat-code: 13px; + --chat-code-lh: 20px; + --chat-title: 24px; + --chat-title-lh: 32px; + --chat-turn-gap: 28px; + --chat-card-pad: 16px; + --chat-icon: 20px; + --chat-mark: 28px; + --chat-control: 32px; + --chat-tap: 0px; + --chat-text-ls: 0.25px; + --chat-key: #f6f8f8; + + --ai-teal-50: #e0f2f1; + --ai-teal-100: #b2dfdb; + --ai-teal-200: #80cbc4; + --ai-teal-300: #4db6ac; + --ai-teal-400: #26a69a; + --ai-teal-500: #00695c; + --ai-teal-600: #00897b; + --ai-teal-700: #00796b; + --ai-teal-800: #00695c; + --ai-teal-900: #004d40; + --ai-deep: #033633; + --ai-deep-hover: #23504e; + --ai-deep-pressed: #002624; + --ai-action: var(--ai-deep); + --ai-action-hover: var(--ai-deep-hover); + --ai-on-action: #ffffff; + --ai-mark-ink-dark: var(--ai-teal-100); + --ai-focus: var(--ai-teal-600); + --ai-selected: var(--ai-teal-500); + --ai-selected-wash: var(--ai-teal-50); + --ai-selected-text: var(--ai-teal-900); + --ai-link: var(--ai-teal-500); + --ai-link-strong: var(--ai-teal-900); + --ai-focus-shadow: color-mix(in srgb, var(--ai-teal-500) 12%, transparent); + --ai-dark: #24323b; + --ai-on-dark: #e6ebee; + --ai-dark-accent: #8fe3d3; + --ai-dark-accent-hover: #a6ecdf; + --ai-dark-accent-soft: #80d6c8; + --ai-dark-accent-pale: #c4f3ea; + --ai-on-dark-accent: #0f2a26; + --ai-person: #e9f0ee; + + --entity-device-bg: #e9efff; + --entity-device-fg: #535eb8; + --entity-path-bg: #dbf5ff; + --entity-path-fg: #007592; + --entity-chain-bg: #f7eaff; + --entity-chain-fg: #814ea4; + --entity-rule-bg: #ffebdf; + --entity-rule-fg: #a34d16; + --entity-view-bg: #e0f7e5; + --entity-view-fg: #2d7b48; + --entity-people-bg: #ffe9f1; + --entity-people-fg: #a0446d; + --entity-solution-bg: #e9f1fb; + --entity-solution-fg: #586a83; + + --tb-code-bg: #1d2830; + --tb-code-fg: #dfe7ec; + --tb-code-line: rgba(255, 255, 255, 0.08); + --tb-code-head-fg: rgba(255, 255, 255, 0.7); + --hl-cmd: var(--ai-dark-accent); + --hl-flag: #9fb6c8; + --hl-str: #f2c98a; + --hl-num: #d4b4f7; + --hl-key: #9cc8f2; + --hl-com: #8a98a3; + --hl-err: #ff9d92; + --hl-fn: #d7e8a3; + --hl-bool: #f3b6d2; + --hl-lvl: #9bdda8; + + --k-grey: var(--tb-ink-76); + --k-faint: var(--tb-text-muted); + --k-stroke: rgba(0, 0, 0, 0.1); + --k-stroke-hover: rgba(0, 0, 0, 0.2); +} + +:root { + --chat-read: 760px; + --chat-read-log: 712px; + --chat-col-min: 340px; + --chat-col-max: 800px; +} + +.ai-chat-col, .sol-chat { + container: k-col / inline-size; +} + +@container k-col (max-width: 480px) { + * { + --chat-turn-gap: 20px; + --chat-card-pad: 12px; + --chat-icon: 18px; + --chat-mark: 24px; + --chat-control: 28px; + } +} + +@media (min-width: 600px) { + @container k-col (max-width: 480px) { + * { + --chat-text: 14px; + --chat-text-lh: 20px; + --chat-head: 14px; + --chat-head-lh: 20px; + --chat-chip: 14px; + --chat-chip-lh: 18px; + --chat-chip-pad: 0px; + --chat-chip-mono: 13px; + --chat-code-lh: 18px; + --chat-title: 20px; + --chat-title-lh: 28px; + } + } +} + +@media (max-width: 1100px) { + .tb-ai-chat.v-panel { + --chat-turn-gap: 20px; + --chat-card-pad: 12px; + --chat-icon: 18px; + --chat-mark: 24px; + --chat-control: 28px; + } +} + +@media (max-width: 599px) { + .tb-ai-chat { + --chat-turn-gap: 20px; + --chat-card-pad: 12px; + --chat-icon: 18px; + --chat-mark: 24px; + --chat-control: 28px; + } +} + +[data-ai] { + --tb-primary-50: var(--ai-teal-50); + --tb-primary-100: var(--ai-teal-100); + --tb-primary-200: var(--ai-teal-200); + --tb-primary-300: var(--ai-teal-300); + --tb-primary-400: var(--ai-teal-400); + --tb-primary-500: var(--ai-teal-500); + --tb-primary-600: var(--ai-teal-600); + --tb-primary-700: var(--ai-teal-700); + --tb-primary-800: var(--ai-teal-800); + --tb-primary-900: var(--ai-teal-900); + --tb-primary-contrast-500: #ffffff; +} + +.tb-ai-mark { + --m: 28px; + --ai-spark: .66; + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: var(--m); + height: var(--m); + border-radius: 38%; + background: var(--ai-mark-fill); + background-size: 240% 240%; + box-shadow: var(--ai-mark-edge); + animation: tb-ai-icon-flow 8s ease-in-out infinite alternate; + + > .mat-icon { + font-family: 'Material Icons Round'; + font-size: calc(var(--m) * var(--ai-spark)); + width: calc(var(--m) * var(--ai-spark)); + height: calc(var(--m) * var(--ai-spark)); + line-height: 1; + color: var(--ai-mark-ink) !important; + background: var(--ai-mark-ink-fill); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + } + + > .ai-spark-svg { + display: block; + flex: none; + width: calc(var(--m) * var(--ai-spark)); + height: calc(var(--m) * var(--ai-spark)); + + svg { + display: block; + overflow: visible; + } + } + + &.lg { + --ai-spark: .74; + box-shadow: var(--ai-mark-edge), 0 1px 2px rgb(16 24 40 / 0.06), 0 8px 24px color-mix(in oklab, var(--ai-light-teal) 26%, transparent); + } + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +.ai-spark-svg stop:nth-child(1) { stop-color: var(--ai-mark-ink-a); } +.ai-spark-svg stop:nth-child(2) { stop-color: var(--ai-mark-ink-b); } +.ai-spark-svg stop:nth-child(3) { stop-color: var(--ai-mark-ink-c); } + +@keyframes tb-ai-icon-flow { + 0% { background-position: 0% 0%; } + 50% { background-position: 100% 60%; } + 100% { background-position: 40% 100%; } +} + +.tb-ai-status-mark { + flex: none; + width: 12px; + height: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + + &::before { + content: ''; + display: block; + } + + &.needs::before { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--tb-caution); + } + + &.nodata::before { + width: 8px; + height: 8px; + box-sizing: border-box; + border-radius: 50%; + border: 2px solid var(--tb-caution); + } + + &.error::before { + width: 6px; + height: 6px; + border-radius: 1px; + background: var(--tb-crit); + transform: rotate(45deg); + } + + &.running::before { + width: 9px; + height: 9px; + box-sizing: border-box; + border-radius: 50%; + border: 2px solid var(--tb-ink-38); + border-top-color: transparent; + animation: tb-ai-status-turn .9s linear infinite; + } + + @media (prefers-reduced-motion: reduce) { + &.running::before { + animation: none; + border-top-color: var(--tb-ink-38); + } + } +} + +.ai-chat-status .tb-ai-status-mark.running::before { + animation: none; + border-top-color: var(--tb-ink-38); +} + +@keyframes tb-ai-status-turn { + to { transform: rotate(360deg); } +} + +.mat-mdc-menu-panel.tb-ai-chat-menu { + min-width: 200px; + max-width: 300px; + + .tb-ai-menu-h { + margin: 6px 0 0; + padding: 6px 10px 4px; + border-top: 1px solid var(--tb-line); + font: 500 11.5px/16px var(--tb-font); + color: var(--tb-ink-54); + } + + .mat-mdc-menu-item:first-child + .tb-ai-menu-h, .tb-ai-menu-h:first-child { + margin-top: 0; + border-top: 0; + } + + .tb-ai-menu-chat { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + + .t { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .tb-ai-status-mark { + flex: none; + } + } + border-radius: 12px; + background: var(--tb-surface); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06), 0 4px 12px rgba(16, 24, 40, 0.10), 0 12px 32px rgba(16, 24, 40, 0.10); + + .mat-mdc-menu-content { + padding: 6px; + } + + .mat-mdc-menu-item { + min-height: 34px; + height: 34px; + padding: 0 10px; + border-radius: 8px; + gap: 10px; + + .mat-mdc-menu-item-text { + font: 400 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + } + + .mat-icon { + margin-right: 0; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + color: var(--tb-ink-60); + } + + &:hover:not([disabled]), &.cdk-program-focused, &.cdk-keyboard-focused { + background: rgba(0, 0, 0, 0.05); + } + + &.danger { + position: relative; + margin-top: 7px; + overflow: visible; + + &::before { + content: ''; + display: block; + position: absolute; + left: 4px; + right: 4px; + top: -4px; + bottom: auto; + height: 1px; + border: 0; + border-radius: 0; + background: rgba(0, 0, 0, 0.08); + } + + .mat-mdc-menu-item-text, .mat-icon { + color: var(--tb-crit); + } + + &:hover:not([disabled]) { + background: var(--tb-crit-tint); + } + } + } +} + +.mat-mdc-tooltip.tb-ai-cursor-tooltip { + translate: -12px 30px; +} + +@mixin tb-ai-kbd { + 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; + flex: none; +} + +.tb-popover.tb-ai-tip { + .tb-popover-inner { + border-radius: 8px; + background-color: #1f2a31; + box-shadow: 0 6px 20px rgba(16, 24, 40, 0.22); + } + + .tb-popover-inner-content { + padding: 0; + overflow: visible; + } + + &[class*='tb-popover-placement-top'] > .tb-popover-content > .tb-popover-arrow { + border-right-color: #1f2a31; + border-bottom-color: #1f2a31; + box-shadow: none; + } + + &[class*='tb-popover-placement-bottom'] > .tb-popover-content > .tb-popover-arrow { + border-top-color: #1f2a31; + border-left-color: #1f2a31; + box-shadow: none; + } + + .tb-ai-tip-body { + box-sizing: border-box; + width: max-content; + max-width: min(248px, calc(100vw - 16px)); + padding: 9px 12px 10px; + color: #d5dde2; + font: 400 12px/17px var(--tb-font); + letter-spacing: .1px; + + b { + display: block; + margin: 0; + font-size: 13px; + line-height: 18px; + font-weight: 500; + color: var(--ai-on-action); + } + + p { + margin: 0; + font: inherit; + letter-spacing: inherit; + } + + p + p { + margin-top: 3px; + } + + .tip-value { + font-weight: 500; + color: #c3ced5; + + &.on { + color: var(--ai-dark-accent); + } + } + + .tip-sub { + color: #9fadb7; + } + + .tip-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 16px; + margin-bottom: 3px; + } + + .tip-keyrow { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + min-height: 22px; + } + + .tip-caps { + display: inline-flex; + gap: 3px; + } + + kbd { + @include tb-ai-kbd; + min-width: 18px; + height: 18px; + border: 0; + background: rgba(255, 255, 255, 0.14); + color: #fff; + } + + &.tip-keys { + min-width: 208px; + + .tip-head { + margin-bottom: 2px; + } + } + + &.tip-mini { + padding: 5px 8px 6px; + + .tip-keyrow { + gap: 10px; + min-height: 18px; + } + } + } +} + +:root { + --entity-device-bg: #e9efff; + --entity-device-fg: #535eb8; + --entity-path-bg: #dbf5ff; + --entity-path-fg: #007592; + --entity-chain-bg: #f7eaff; + --entity-chain-fg: #814ea4; + --entity-rule-bg: #ffebdf; + --entity-rule-fg: #a34d16; + --entity-view-bg: #e0f7e5; + --entity-view-fg: #2d7b48; + --entity-people-bg: #ffe9f1; + --entity-people-fg: #a0446d; + --entity-solution-bg: #e9f1fb; + --entity-solution-fg: #586a83; +} + +.tb-rec { + min-width: 0; + font-family: var(--tb-font, Roboto, sans-serif); + + &.line { + display: flex; + align-items: center; + gap: 8px; + width: fit-content; + max-width: 100%; + min-height: 32px; + padding: 3px 10px 3px 5px; + box-sizing: border-box; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + + .tb-rec-meta { + flex-shrink: 100000; + min-width: 72px; + } + + .tb-ai-state { + flex: none; + } + } + + &[data-pal="device"] .tb-rec-tile { background: var(--entity-device-bg); color: var(--entity-device-fg); } + &[data-pal="path"] .tb-rec-tile { background: var(--entity-path-bg); color: var(--entity-path-fg); } + &[data-pal="chain"] .tb-rec-tile { background: var(--entity-chain-bg); color: var(--entity-chain-fg); } + &[data-pal="rule"] .tb-rec-tile { background: var(--entity-rule-bg); color: var(--entity-rule-fg); } + &[data-pal="view"] .tb-rec-tile { background: var(--entity-view-bg); color: var(--entity-view-fg); } + &[data-pal="people"] .tb-rec-tile { background: var(--entity-people-bg); color: var(--entity-people-fg); } + &[data-pal="solution"] .tb-rec-tile { background: var(--entity-solution-bg); color: var(--entity-solution-fg); } +} + +.tb-rec-badge { + flex: none; + display: inline-flex; + align-items: center; + height: 18px; + margin-left: 6px; + padding: 0 6px; + border-radius: 4px; + font: 600 10px/16px var(--tb-mono); + letter-spacing: .5px; + color: var(--tb-ink-54); + background: var(--tb-ink-12); + vertical-align: middle; + + &[data-badge="pdf"] { + color: var(--tb-crit); + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + } + + &[data-badge="csv"] { + color: var(--tb-ok-text); + background: var(--tb-ok-tint); + } +} + +.tb-rec-tile { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: 24px; + height: 24px; + border-radius: 6px; + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink-76); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + color: inherit; + } +} + +.tb-rec-name { + min-width: 0; + flex: 0 1 auto; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--tb-ink); + font-weight: 500; + text-decoration: none; +} + +.tb-rec a.tb-rec-name { + font-weight: 500; + color: var(--tb-ink); + border-bottom: 0; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + transition: text-decoration-color .15s ease; + + &:hover, &:focus, &:focus-visible { + border-bottom: 0; + color: var(--tb-ink); + text-decoration-color: var(--tb-ink-54); + } +} + +.tb-rec-meta { + flex: 0 1 auto; + min-width: 0; + font-size: 12px; + line-height: 16px; + color: var(--tb-ink-76); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.tb-ai-state { + display: inline-flex; + align-items: center; + gap: 6px; + height: 24px; + padding: 0 10px 0 8px; + border-radius: 12px; + font-size: 12px; + line-height: 16px; + font-weight: 500; + letter-spacing: .2px; + color: #fff; + background: var(--tb-ink-54); + white-space: nowrap; + vertical-align: middle; + + i { + width: 7px; + height: 7px; + border-radius: 50%; + background: currentColor; + } +} + +.tb-rec .tb-ai-state { + height: 20px; + gap: 5px; + padding: 0 8px 0 7px; + border-radius: 10px; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + letter-spacing: .1px; + color: var(--tb-ok-text); + background: color-mix(in srgb, var(--tb-ok) 10%, transparent); + box-shadow: none; + + i { + width: 6px; + height: 6px; + } + + &.off { + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + } + + &.warn, &.wait { + color: var(--tb-caution-text); + background: color-mix(in srgb, var(--tb-caution) 11%, transparent); + } + + &.wait i { + animation: tb-wait-pulse 1.6s ease-in-out infinite; + } + + &.hub { + padding-left: 6px; + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + + .mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + color: var(--tb-ink-54); + } + } + + &.sev { + padding-left: 6px; + color: var(--sv-t); + background: color-mix(in srgb, var(--sv) 10%, transparent); + + &.critical { --sv: var(--tb-sev-critical); --sv-t: var(--tb-sev-critical); } + &.major { --sv: var(--tb-sev-major); --sv-t: var(--tb-sev-major-text); } + &.minor { --sv: var(--tb-sev-minor); --sv-t: var(--tb-sev-minor-text); } + &.warning { --sv: var(--tb-sev-warning); --sv-t: var(--tb-sev-warning-text); } + &.indeterminate { --sv: var(--tb-sev-indeterminate); --sv-t: var(--tb-ink-76); } + + &.cleared { + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + + .tb-sev-mark { + --m: var(--tb-ink-38); + + .r, .d { + stroke: var(--tb-ink-38); + } + } + } + } + + .tb-ack-ic { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + margin: 0 -2px 0 -1px; + } +} + +.tb-ai-facts { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + align-items: baseline; + gap: 2px 12px; + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + + dt { + color: var(--tb-text-muted); + font-size: var(--chat-meta); + } + + dd { + margin: 0; + color: var(--tb-ink); + } +} + +.tb-ai-more { + display: inline-flex; + align-items: center; + gap: 4px; + margin: 4px 0 0 -4px; + padding: 2px 6px 2px 4px; + border: 0; + border-radius: 6px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-primary-500); + cursor: pointer; + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + line-height: 16px; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } +} + +.tb-disc { + > summary { + list-style: none; + display: flex; + align-items: center; + gap: 4px; + width: fit-content; + cursor: pointer; + font-family: var(--tb-font); + color: var(--tb-ink-60); + + &::-webkit-details-marker { + display: none; + } + + &::before { + content: 'chevron_right'; + flex: none; + width: 18px; + height: 18px; + font: 18px/18px 'Material Icons'; + color: var(--tb-ink-38); + transition: transform .15s ease; + } + + &:hover, &:hover::before { + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 4px; + } + } + + &[open] > summary::before { + transform: rotate(90deg); + } + + &.tb-disc-details { + margin-top: 6px; + + > summary { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + } + + > :not(summary) { + margin-top: 8px; + } + } +} + +.k-recs { + display: grid; + gap: 6px; + margin-top: 14px; + + .tb-rec { + margin: 0; + } +} + +.tb-rec.card { + position: relative; + display: block; + margin-top: 14px; + padding: 10px 12px 12px; + border-radius: 12px; + background: var(--tb-surface); + border: 1px solid var(--tb-line); + box-sizing: border-box; + color: var(--tb-ink); + + .tb-rec-row { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + align-items: center; + } + + .tb-rec-tile { + width: 40px; + height: 40px; + border-radius: 10px; + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + line-height: 22px; + } + } + + &.with-pic .tb-rec-row { + min-height: 58px; + } + + .tb-rec-pic { + display: flex; + align-items: center; + justify-content: center; + align-self: stretch; + width: 120px; + margin: -10px 12px -12px -12px; + padding: 0; + box-sizing: border-box; + border-right: 1px solid var(--tb-line); + border-radius: 11px 0 0 11px; + background: #eef1f3; + overflow: hidden; + + &:has(svg) { + background: #fff; + } + + img, svg { + display: block; + width: 100%; + height: 100%; + } + + img { + object-fit: cover; + object-position: top center; + } + + > .tb-rec-tile { + display: none; + } + } + + .tb-rec-img { + display: contents; + } + + &.tight .tb-rec-pic { + align-self: start; + width: auto; + min-height: 0; + margin: 0 12px 0 0; + border: 0; + border-radius: 0; + background: none; + grid-row: 1; + + > :not(.tb-rec-tile) { + display: none; + } + + > .tb-rec-tile { + display: inline-flex; + } + } + + .tb-rec-body { + min-width: 0; + display: flex; + flex-direction: column; + gap: 2px; + } + + .tb-rec-title { + font-weight: 500; + font-size: 15px; + line-height: 20px; + color: var(--tb-ink); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + text-decoration: none; + } + + a.tb-rec-title { + border-bottom: 0; + text-decoration: none; + + &:hover, &:focus-visible { + border-bottom: 0; + color: var(--tb-ink); + text-decoration: none; + } + + &::after { + content: ''; + position: absolute; + inset: 0; + border-radius: 11px; + } + + &:focus-visible { + outline: none; + } + + &:focus-visible::after { + outline: 2px solid var(--tb-primary-300); + outline-offset: 2px; + } + } + + &.with-details > .tb-rec-row { + position: relative; + } + + &.with-details a.tb-rec-title { + &::after { + inset: -8px -10px; + border-radius: 9px; + } + + &:focus-visible::after { + outline-offset: 0; + } + } + + :is(.tb-open, .tb-open-btn, .tb-rec-act, .tb-ai-state.hub) { + position: relative; + z-index: 1; + } + + &:has(a.tb-rec-title:hover) .tb-open { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:has(a.tb-rec-title:hover) .tb-open-btn { + background: var(--ai-action-hover); + } + + .tb-rec-side .tb-open-btn.icon.mat-mdc-unelevated-button { + width: 36px; + min-width: 36px; + padding: 0; + gap: 0; + justify-content: center; + overflow: visible; + + > .mat-icon.mat-icon { + margin: 0; + } + + > .mdc-button__label:empty { + display: none; + } + } + + .tb-rec-meta { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .tb-rec-side { + display: flex; + align-items: center; + gap: 6px; + margin: 0 -4px 0 8px; + } + + &.primary .tb-rec-side { + margin: 0 0 0 12px; + } + + &.tight.primary:not(.open-icon) { + .tb-rec-row { + align-items: start; + } + + .tb-rec-side { + grid-column: 2 / -1; + grid-row: 2; + margin: 10px 0 0; + justify-self: stretch; + } + + .tb-open-btn { + width: 100%; + justify-content: center; + } + } + + .tb-rec-pic { + &.sq { + width: 80px; + background: #fff; + + img { + object-fit: contain; + padding: 4px; + box-sizing: border-box; + } + } + + &.wide { + width: 160px; + } + } + + &.with-pic.with-details .tb-rec-pic { + border-bottom-left-radius: 0; + } + + .tb-open { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--tb-ink-54); + text-decoration: none; + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } + } + + .tb-rec-det { + display: grid; + gap: 8px; + margin: 10px -12px -12px; + padding: 10px 12px 12px; + border-top: 1px solid var(--tb-line); + border-radius: 0 0 11px 11px; + background: rgba(16, 24, 40, 0.03); + + > .k-chips { + margin: 2px 0 0; + } + } + + .tb-rec-note { + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .tb-ai-facts code { + padding: 1px 5px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: .92em; + } + + .tb-rec-meta .tight-only { + display: none; + } + + .tb-rec-side { + min-width: 0; + } + + &.tight { + .tb-rec-meta .tight-only { + display: inline-flex; + } + + .tb-rec-side > .tb-ai-state.hub { + display: none; + } + + &.primary:not(.open-icon) .tb-open-btn { + flex: 1 1 auto; + width: auto; + } + } +} + +.k-time { + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); + font-variant-numeric: tabular-nums; +} + +.k-review { + position: relative; + padding: calc(var(--chat-card-pad) - 2px) var(--chat-card-pad); + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + font-family: var(--tb-font); + font-size: 14px; + line-height: 20px; + letter-spacing: .25px; + color: var(--tb-ink); + + > .k-head { + display: flex; + align-items: center; + gap: 6px; + padding-right: 44px; + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + font-weight: 500; + color: var(--tb-ink); + + > .mat-icon { + margin-top: 1px; + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); + line-height: var(--chat-icon); + color: var(--tb-ink-54); + } + } + + > .k-time { + position: absolute; + right: 16px; + top: 14px; + margin-left: 8px; + } + + .tb-rec.line { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto; + column-gap: 12px; + row-gap: 2px; + align-items: center; + width: auto; + margin: 0; + padding: 10px 0; + border: 0; + border-top: 1px solid var(--tb-line); + border-radius: 0; + background: none; + + .tb-rec-tile { + width: 40px; + height: 40px; + border-radius: 10px; + grid-row: 1 / span 2; + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + line-height: 22px; + } + } + + .tb-rec-name { + grid-column: 2; + grid-row: 1; + font-size: var(--chat-line); + } + + .tb-rec-meta { + grid-column: 2; + grid-row: 2; + min-width: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + } + + > .tb-ai-state { + grid-column: 3; + grid-row: 1 / span 2; + } + + &.closed { + border-bottom: 1px solid var(--tb-line); + } + + &.planned .tb-rec-tile { + background: transparent; + border: 1.5px dotted currentColor; + box-sizing: border-box; + } + } + + > .k-head + .tb-rec.line { + margin-top: 10px; + } + + &.auto { + padding: 4px 0 2px; + background: transparent; + border: 0; + + > .k-head { + color: var(--tb-text-secondary); + font-size: var(--chat-line); + } + } + + &.done > .k-head > .mat-icon { + color: var(--tb-ok); + } + + &.failed > .k-head > .mat-icon { + color: var(--tb-crit); + } + + &.expired > .k-head, + &.denied > .k-head { + color: var(--tb-text-secondary); + } +} + +.k-review-p { + margin: 8px 0 0; + letter-spacing: .25px; + font-size: 14.5px; + line-height: 21px; + color: var(--tb-ink); + + .k-review.expired &, + .k-review.denied & { + color: var(--tb-text-secondary); + } +} + +.k-fields { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + align-items: baseline; + gap: 6px 14px; + margin: 12px 0 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + + dt { + color: var(--tb-ink-76); + } + + dd { + margin: 0; + color: var(--tb-ink); + overflow-wrap: anywhere; + } +} + +.k-detail-images { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--tb-text-muted); +} + +.k-detail-img { + display: block; + width: 100px; + height: 80px; + object-fit: contain; + border: 1px solid var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + background: #fff; + + &.was { + opacity: .6; + } +} + +.k-review .k-img { + display: block; + width: 150px; + height: 120px; + object-fit: contain; + border: 1px solid var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + background: #fff; + + &.was { + opacity: .6; + } +} + +.k-review code, +.k-diff code { + display: inline-block; + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: 14px; + line-height: 18px; + color: var(--tb-ink); + white-space: normal; + overflow-wrap: anywhere; +} + +.k-diff { + border-collapse: collapse; + margin: 12px 0 0; + font-size: 15px; + line-height: 22px; + + thead th { + padding: 0 24px 4px 0; + font: 500 12px/16px var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + color: var(--tb-text-muted); + text-align: left; + } + + tbody th { + padding: 5px 24px 5px 0; + font-size: 15px; + font-weight: 400; + color: var(--tb-text-muted); + text-align: left; + vertical-align: baseline; + + code { + white-space: nowrap; + overflow-wrap: normal; + } + } + + td { + padding: 5px 24px 5px 0; + font-size: 15px; + vertical-align: baseline; + white-space: nowrap; + + &:last-child { + padding-right: 0; + } + } + + .k-diff-was { + color: var(--tb-text-secondary); + } + + td.k-diff-was, td.k-diff-now { + white-space: normal; + overflow-wrap: break-word; + } + + .k-diff-now span { + box-decoration-break: clone; + -webkit-box-decoration-break: clone; + margin-left: -6px; + padding: 1px 6px; + border-radius: 4px; + background: var(--ai-teal-50); + color: var(--tb-ink); + font-weight: 500; + } + + .k-diff-same { + td { + color: var(--tb-text-secondary); + white-space: normal; + } + + tr:first-child > * { + padding-top: 9px; + } + } +} + +.k-actions { + display: flex; + align-items: center; + gap: 10px; + margin-top: 14px; +} + +.k-actions, .tb-rec-side, .art-pane-foot { + .mdc-button { + height: 36px; + gap: 8px; + border: 1px solid transparent; + border-radius: 4px; + line-height: 36px; + letter-spacing: .4375px; + white-space: nowrap; + + .mdc-button__label { + line-height: 36px; + white-space: nowrap; + } + + &.mdc-button > .mat-icon.mat-icon { + margin: 0 0 0 -4px; + } + } + + .mat-mdc-unelevated-button:not(:disabled) { + --mat-button-filled-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); + padding: 0 16px; + } + + .mat-mdc-unelevated-button.warn:not(:disabled) { + --mat-button-filled-container-color: var(--tb-crit); + } + + .mat-mdc-button:not(:disabled) { + --mat-button-text-label-text-color: var(--tb-ink-76); + padding: 0 8px; + } + + .mat-mdc-outlined-button:not(:disabled) { + --mat-button-outlined-label-text-color: var(--tb-ink-76); + --mat-button-outlined-outline-color: var(--k-stroke); + background: var(--tb-surface); + } + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } +} + +.k-deny { + margin-top: 10px; +} + +@media (min-width: 1101px) { + html.tb-ai-docked .cdk-overlay-container { + .cdk-overlay-dark-backdrop { + right: var(--tb-ai-panel-w, 364px); + } + + .cdk-global-overlay-wrapper:has(.mat-mdc-dialog-container) { + width: calc(100% - var(--tb-ai-panel-w, 364px)); + } + } +} + +body.tb-ai-resizing { + cursor: ew-resize !important; + user-select: none; +} + +.k-hint { + display: flex; + gap: 8px; + align-items: flex-start; + font-size: 14px; + line-height: 20px; + color: var(--k-grey); + + > .mat-icon.mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-54); + } + + b { + font-weight: 500; + color: var(--tb-ink); + } +} + +.k-start { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-54); + + &::before, &::after { + content: ''; + flex: 1 0 16px; + height: 1px; + background: var(--tb-line); + } + + &[hidden] { + display: none; + } + + > span { + flex: none; + } + + > a.tb-chiplink { + display: block; + flex: 0 1 auto; + min-width: 0; + max-width: 75%; + border-radius: 6px; + color: inherit; + text-decoration: none; + border-bottom: 0; + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +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; +} + +.k-start code.k-ent { + overflow: hidden; + text-overflow: ellipsis; + vertical-align: top; +} + +code.k-ent .k-ent-ic { + display: inline-block; + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + margin: 0 5px 0 -2px; + vertical-align: -3px; + color: var(--tb-ink-76); +} + +code.k-ent[data-pal="device"] .k-ent-ic { color: var(--entity-device-fg); } +code.k-ent[data-pal="path"] .k-ent-ic { color: var(--entity-path-fg); } +code.k-ent[data-pal="chain"] .k-ent-ic { color: var(--entity-chain-fg); } +code.k-ent[data-pal="rule"] .k-ent-ic { color: var(--entity-rule-fg); } +code.k-ent[data-pal="view"] .k-ent-ic { color: var(--entity-view-fg); } +code.k-ent[data-pal="people"] .k-ent-ic { color: var(--entity-people-fg); } +code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); } + +.k-sev { + padding: 2px 7px 2px 5px; + border-radius: 5px; + font-family: var(--tb-font); + font-size: 14px; + font-weight: 500; + white-space: nowrap; + color: var(--sv-t); + background: color-mix(in srgb, var(--sv) 10%, transparent); + + .tb-sev-mark { + margin-right: 4px; + vertical-align: -1px; + } + + &.critical { --sv: var(--tb-sev-critical); --sv-t: var(--tb-sev-critical); } + &.major { --sv: var(--tb-sev-major); --sv-t: var(--tb-sev-major-text); } + &.minor { --sv: var(--tb-sev-minor); --sv-t: var(--tb-sev-minor-text); } + &.warning { --sv: var(--tb-sev-warning); --sv-t: var(--tb-sev-warning-text); } + &.indeterminate { --sv: var(--tb-sev-indeterminate); --sv-t: var(--tb-ink-76); } +} + +.tb-sev-mark { + display: inline-flex; + flex: none; + vertical-align: middle; + + svg { display: block; overflow: visible; } + .f { fill: var(--m); stroke: var(--m); stroke-width: .6; stroke-linejoin: round; } + .g { fill: #fff; } + .r { fill: none; stroke: var(--tb-sev-warning); stroke-width: 1.7; } + .d { fill: none; stroke: var(--tb-sev-indeterminate); stroke-width: 1.8; stroke-linecap: round; stroke-dasharray: 0 2; } + + &.critical { --m: var(--tb-sev-critical); } + &.major { --m: var(--tb-sev-major); } + &.minor { --m: var(--tb-sev-minor); } +} + +.k-chips { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.k-plan { + max-width: 680px; + padding: 12px 14px 14px; + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + font-family: var(--tb-font); + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + + .k-plan-head { + display: flex; + align-items: center; + gap: 6px; + min-height: 28px; + margin: -4px -6px 0 0; + font-size: 14px; + line-height: 20px; + font-weight: 500; + color: var(--tb-ink); + + .tb-spacer { + flex: 1; + } + } + + .k-plan-count { + font-weight: 400; + font-size: var(--chat-meta); + color: var(--k-faint); + } + + ol { + display: grid; + gap: 6px; + margin: 6px 0 0; + padding: 0; + list-style: none; + } + + li { + display: grid; + grid-template-columns: 16px minmax(0, 1fr); + gap: 10px; + align-items: start; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + &:is(.done, .off, .unchecked) .k-what { + color: var(--tb-text-secondary); + } + + &.now .k-what { + color: var(--tb-ink); + } + } + + .k-what code.k-ent { + font-size: var(--chat-code); + line-height: var(--chat-chip-lh); + padding: 0 6px; + + .k-ent-ic { + width: calc(var(--chat-code) + 1px); + height: calc(var(--chat-code) + 1px); + font-size: calc(var(--chat-code) + 1px); + line-height: calc(var(--chat-code) + 1px); + } + } + + .k-what code:not(.k-ent) { + display: inline-block; + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: 14px; + line-height: 18px; + white-space: nowrap; + } + + .k-check { + width: 14px; + height: 14px; + margin: 3.5px 0 0; + accent-color: var(--ai-deep); + justify-self: center; + cursor: pointer; + } + + .k-plan-foot { + flex-wrap: wrap; + gap: 8px; + margin: 14px -14px 0; + padding: 12px 14px 0; + border-top: 1px solid var(--k-stroke); + } +} + +.k-pmark { + box-sizing: border-box; + display: inline-flex; + align-items: center; + justify-content: center; + justify-self: center; + width: 14px; + height: 14px; + margin-top: 3.5px; + border-radius: 50%; + border: 1.5px solid var(--tb-ink-38); + + &.now { + border-color: var(--tb-ink); + + &::after { + content: ''; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--tb-ink); + } + } + + &.done { + border: 0; + background: var(--tb-ok); + color: #fff; + } + + &.off { + border-style: dashed; + color: var(--tb-ink-38); + + .mat-icon { + display: none; + } + } + + .mat-icon { + width: 11px; + height: 11px; + font-size: 11px; + line-height: 11px; + font-weight: 700; + } +} + +.k-you { + display: inline-block; + margin-right: 4px; + padding: 0 5px; + border-radius: 4px; + background: var(--ai-deep); + color: var(--ai-on-action); + font: 500 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + vertical-align: 1px; +} + +.k-need { + display: inline-block; + margin-right: 6px; + padding: 0 5px; + border-radius: 4px; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.28); + color: var(--tb-ink-76); + font: 500 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + vertical-align: 1px; + white-space: nowrap; +} + +.k-iconbtn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + 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; + } +} + +.k-offer { + display: grid; + grid-template-columns: 28px minmax(0, 1fr); + gap: 10px 12px; + align-items: start; + max-width: 680px; + padding: 12px 16px 12px 14px; + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + font-family: var(--tb-font); + font-size: 15px; + line-height: 22px; + color: var(--tb-ink-76); + + > span:not(.k-chips) { + min-width: 0; + } + + .k-offer-ic { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border-radius: 50%; + background: var(--ai-teal-500); + color: #fff; + + .mat-icon { + width: 17px; + height: 17px; + font-size: 17px; + line-height: 17px; + color: inherit; + } + } + + .k-chips { + grid-column: 2; + align-items: center; + gap: 6px 8px; + margin: 0; + } + + .ob-chip { + padding: 0 12px; + } + + .ob-chip.k-chip-quiet { + border-color: transparent; + background: transparent; + color: var(--tb-ink-76); + + &:hover { + background: rgba(0, 0, 0, 0.05); + border-color: transparent; + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +.ob-chip { + display: inline-flex; + align-items: center; + gap: 6px; + height: var(--chat-control); + padding: 0 14px; + box-sizing: border-box; + border-radius: 16px; + border: 1px solid var(--tb-line); + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: calc(var(--chat-control) - 2px); + letter-spacing: .1px; + color: var(--tb-ink-76); + cursor: pointer; + transition: background-color .15s, border-color .15s; + + &:hover { + background: rgba(0, 0, 0, 0.04); + border-color: rgba(0, 0, 0, 0.2); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &[aria-pressed="true"] { + background: var(--ai-selected-wash); + color: var(--ai-selected-text); + border-color: var(--ai-selected); + box-shadow: inset 0 0 0 1px var(--ai-selected); + } + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + color: inherit; + } +} + +.k-chips.agent-chips .ob-chip { + height: auto; + min-height: var(--chat-control); + padding-top: calc((var(--chat-control) - 22px) / 2); + padding-bottom: calc((var(--chat-control) - 22px) / 2); + line-height: 20px; + text-align: left; +} + +.k-deny-in { + width: 100%; + box-sizing: border-box; + height: 36px; + padding: 0 12px; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font: 400 14px/34px var(--tb-font); + color: var(--tb-ink); + + &::placeholder { + color: var(--k-faint); + } + + &:focus { + outline: 0; + border-color: var(--ai-focus); + box-shadow: 0 0 0 1px var(--ai-focus); + } +} + +@container k-chat (max-width: 560px) { + .k-fields { + grid-template-columns: minmax(0, 1fr); + gap: 1px 0; + + dt { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + dd { + margin-bottom: 6px; + + &:last-child { + margin-bottom: 0; + } + } + } + + .k-actions { + flex-wrap: wrap; + } +} + +@mixin k-diff-stacked { + thead { + display: none; + } + + tr { + display: block; + padding: 4px 0; + } + + tbody th { + display: block; + padding: 0; + } + + td { + display: inline; + padding: 0; + } + + .k-diff-now::before { + content: '→'; + margin: 0 12px 0 8px; + color: var(--tb-ink-38); + } +} + +.k-diff.k-diff-stacked { + @include k-diff-stacked; + + td.k-diff-was:not(:empty) { + text-decoration: line-through; + } +} + +@container k-chat (max-width: 420px) { + .k-diff { + thead { + display: none; + } + + tr { + display: block; + padding: 4px 0; + } + + tbody th { + display: block; + padding: 0; + } + + td { + display: inline; + padding: 0; + } + + .k-diff-now::before { + content: '→'; + margin: 0 12px 0 8px; + color: var(--tb-ink-38); + } + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-disc > summary::before { + transition: none; + } +} + +.k-ask { + position: relative; + display: grid; + gap: 12px; + padding: calc(var(--chat-card-pad) - 2px) var(--chat-card-pad); + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + box-shadow: none; + font-family: var(--tb-font); + font-size: 14px; + line-height: 20px; + letter-spacing: .25px; + color: var(--tb-ink); + + > .k-head { + display: flex; + align-items: center; + gap: 6px; + padding-right: 44px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink); + + > .mat-icon { + margin-top: 1px; + color: var(--tb-ink-54); + } + + .k-sub { + font-weight: 400; + font-size: var(--chat-meta); + } + + .k-count { + margin-left: 2px; + } + } + + &.stepped { + gap: 14px; + + .k-step { + display: grid; + gap: 12px; + + &.in-next, &.in-back { + animation: k-fade-through .15s cubic-bezier(.2, 0, 0, 1); + } + } + } + + .k-ask-q { + b { + display: block; + font-size: 17px; + line-height: 24px; + font-weight: 500; + color: var(--tb-ink); + } + + .k-why { + display: block; + align-items: flex-start; + gap: 6px; + margin-top: 3px; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink-76); + } + } + + .k-ask-a > * + * { + margin-top: 10px; + } + + .k-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + margin-top: 0; + + .mat-mdc-button:not(:disabled) { + color: var(--tb-ink-76); + } + + .tb-spacer { + flex: 1; + } + + .mdc-button { + transition: opacity .15s ease, background-color .15s ease; + + &:disabled { + opacity: .45; + cursor: default; + } + } + } + + .k-optbody span { + font-size: 13.5px; + line-height: 18px; + color: var(--tb-ink-76); + } + + .ob-chip:disabled { + cursor: default; + opacity: 1; + } + + > .k-time { + position: absolute; + right: 16px; + top: 14px; + margin-left: 8px; + } + + &.answered { + container-type: inline-size; + gap: 8px; + padding: 10px 16px; + background: var(--tb-surface); + box-shadow: none; + + > .k-head { + color: var(--tb-ink-76); + } + + .k-q { + display: grid; + grid-template-columns: minmax(0, max-content) minmax(min(100%, 35%), 1fr); + align-items: baseline; + gap: 10px; + } + + .k-qt { + font-size: 14px; + line-height: 22px; + color: var(--tb-ink-76); + } + + .k-opts { + display: flex; + flex-wrap: wrap; + gap: 8px; + min-width: 0; + } + + .ob-chip[aria-pressed="true"] { + max-width: 100%; + overflow-wrap: anywhere; + height: auto; + min-height: 0; + padding: 0; + border: 0; + border-radius: 0; + background: none; + box-shadow: none; + font-size: 15px; + line-height: 22px; + font-weight: 500; + color: var(--tb-ink); + white-space: normal; + text-align: left; + } + + @container (max-width: 560px) { + .k-q { + grid-template-columns: minmax(0, 1fr); + gap: 1px; + } + + .k-q + .k-q { + margin-top: 6px; + } + + .k-qt { + font-size: 13px; + line-height: 18px; + } + + .ob-chip[aria-pressed="true"] { + font-size: 14px; + line-height: 20px; + } + } + } +} + +.k-optcards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(max(150px, calc((100% - (var(--n, 3) - 1) * 8px) / var(--n, 3))), 1fr)); + gap: 8px; + + &.list { + grid-template-columns: minmax(0, 1fr); + + .k-optcard { + padding: 12px 14px; + } + + .k-optbody b { + font-size: 15px; + line-height: 21px; + font-weight: 400; + } + + .k-optcard[aria-checked="true"] .k-optbody b { + font-weight: 500; + } + } + + > .k-optcard.other { + grid-column: 1 / -1; + } +} + +.k-optcard { + display: grid; + grid-template-columns: 18px minmax(0, 1fr); + gap: 10px; + align-items: start; + padding: 10px 12px; + border: 1px solid var(--tb-line); + border-radius: 10px; + background: var(--tb-surface); + font: inherit; + letter-spacing: normal; + color: var(--tb-ink); + text-align: left; + cursor: pointer; + transition: background-color .1s cubic-bezier(.2, 0, 0, 1), border-color .1s cubic-bezier(.2, 0, 0, 1), box-shadow .1s cubic-bezier(.2, 0, 0, 1), color .1s cubic-bezier(.2, 0, 0, 1); + + &:hover { + border-color: rgba(0, 0, 0, 0.25); + background: #fafbfb; + } + + &:active { + background-color: rgba(0, 0, 0, 0.06); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + &[aria-checked="true"] { + letter-spacing: .25px; + border-color: var(--ai-selected); + box-shadow: inset 0 0 0 1px var(--ai-selected); + background: var(--tb-surface); + + .k-optdot { + border-color: var(--ai-selected); + + &::after { + transform: scale(1); + } + } + + .k-optbody b { + color: var(--tb-ink); + } + } + + &.free { + grid-template-columns: minmax(0, 1fr); + } + + &.other { + cursor: text; + + &:focus-within { + border-color: var(--ai-focus); + box-shadow: inset 0 0 0 1px var(--ai-focus); + } + } +} + +.k-optdot { + position: relative; + width: 18px; + height: 18px; + margin-top: 1px; + box-sizing: border-box; + border: 2px solid var(--tb-ink-38); + border-radius: 50%; + transition: border-color .15s ease; + + &::after { + content: ''; + position: absolute; + inset: 3px; + border-radius: 50%; + background: var(--ai-teal-500); + transform: scale(0); + transition: transform .1s cubic-bezier(.2, 0, 0, 1); + } +} + +.k-optcard.multi { + .k-optdot { + border-radius: 4px; + display: inline-flex; + align-items: center; + justify-content: center; + color: #fff; + + &::after { + display: none; + } + + .mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + transform: scale(0); + transition: transform .1s cubic-bezier(.2, 0, 0, 1); + } + } + + &[aria-checked="true"] .k-optdot { + background: var(--ai-selected); + + .mat-icon { + transform: scale(1); + } + } +} + +.k-optbody { + b { + display: block; + font-size: 15px; + line-height: 20px; + font-weight: 500; + color: var(--tb-ink); + } + + span { + display: block; + margin-top: 1px; + font-size: 12.5px; + line-height: 17px; + color: var(--tb-text-secondary); + } +} + +.k-opt-input { + display: block; + width: 100%; + box-sizing: border-box; + margin-top: 3px; + padding: 3px 0 4px; + border: 0; + border-bottom: 1px solid var(--tb-line); + border-radius: 0; + background: transparent; + font: inherit; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + outline: 0; + + &::placeholder { + color: var(--tb-text-muted); + } + + &:focus { + border-bottom-color: var(--tb-ink-54); + } +} + +textarea.k-opt-input { + min-height: 27px; + resize: none; + overflow: hidden; +} + +@keyframes k-fade-through { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .k-ask.stepped .k-step.in-next, .k-ask.stepped .k-step.in-back { + animation: none; + } + + .k-optcard:active { + transform: none; + } +} + +.art-loading { + position: relative; + isolation: isolate; + overflow: hidden; + flex: 1; + min-height: 320px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 24px var(--art-x, 24px); + background: var(--art-bg, var(--tb-surface)); + text-align: center; + + &.k-mark { + --art-dot: color-mix(in srgb, var(--tb-ink) 11%, transparent); + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + background: radial-gradient(circle, var(--art-dot) 2.2px, transparent 2.8px) 0 0 / 24px 24px; + mask-image: radial-gradient(ellipse 58% 54% at 50% 50%, transparent 0%, rgba(0, 0, 0, .35) 55%, #000 100%); + } + } +} + +.art-load-markwrap { + position: relative; + display: inline-flex; + margin-bottom: 12px; + isolation: isolate; +} + +.art-load-glow { + position: absolute; + inset: -22px; + z-index: -1; + border-radius: 50%; + pointer-events: none; + opacity: .55; + filter: blur(16px); + will-change: transform; + background: radial-gradient(40% 40% at 22% 24%, color-mix(in oklab, var(--ai-light-teal) 70%, var(--tb-surface)), transparent 72%), + radial-gradient(38% 38% at 78% 26%, color-mix(in oklab, var(--ai-light-aqua) 60%, var(--tb-surface)), transparent 72%), + radial-gradient(42% 42% at 74% 78%, color-mix(in oklab, var(--ai-light-lilac) 62%, var(--tb-surface)), transparent 72%), + radial-gradient(36% 36% at 24% 76%, color-mix(in oklab, var(--ai-light-peach) 55%, var(--tb-surface)), transparent 72%); + animation: art-glow-turn 14s linear infinite; +} + +@keyframes art-glow-turn { + to { transform: rotate(360deg); } +} + +.art-load-lines { + display: inline-flex; + max-width: 440px; +} + +.art-load-win { + display: grid; + justify-items: center; + max-width: 100%; + height: calc(var(--chat-head-lh) + 6px); + padding-top: 6px; + box-sizing: border-box; + overflow: hidden; + mask-image: linear-gradient(to bottom, transparent 0, #000 8px, #000 calc(100% - 3px), transparent 100%); +} + +.art-load-strip { + grid-area: 1 / 1; + display: grid; + justify-items: center; + align-content: start; + + &.rolling { + animation: art-strip-up .72s cubic-bezier(.3, .7, .2, 1) both; + + .was { + animation: art-line-leave .72s cubic-bezier(.3, .7, .2, 1) both; + } + + .now { + animation: art-line-come .72s cubic-bezier(.3, .7, .2, 1) both; + } + } +} + +.art-load-line { + grid-area: auto; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); +} + +.art-load-ghost { + grid-area: 1 / 1; + height: var(--chat-head-lh); + visibility: hidden; + pointer-events: none; +} + +@keyframes art-strip-up { + from { transform: translateY(0); } + to { transform: translateY(calc(-1 * var(--chat-head-lh))); } +} + +@keyframes art-line-leave { + 60%, to { opacity: 0; } +} + +@keyframes art-line-come { + from, 35% { opacity: 0; } + to { opacity: 1; } +} + +.art-dark .art-load-note { + color: var(--tb-code-head-fg); +} + +.art-load-note { + margin: 2px 0 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + letter-spacing: .25px; + color: var(--k-grey); +} + +@media (prefers-reduced-motion: reduce) { + .art-load-glow { + animation: none; + } + + .art-load-strip.rolling { + animation: none; + + .was { + display: none; + } + + .now { + animation: none; + } + } +} + +.k-pill { + position: absolute; + left: 50%; + bottom: 100%; + z-index: 2; + transform: translateX(-50%); + min-width: 40px; + height: 40px; + padding: 0; + border: 1px solid var(--tb-line); + border-radius: 20px; + background: var(--tb-surface); + box-shadow: 0 2px 8px rgba(16, 24, 40, 0.14); + color: var(--ai-teal-500); + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + cursor: pointer; + + &:hover { + border-color: rgba(0, 0, 0, 0.2); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + &.new { + padding: 0 12px 0 10px; + color: var(--tb-ink); + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + + .mat-icon { + color: var(--ai-teal-500); + } + } + + tb-ai-spin { + --spin: 26px; + } + + &:not(.new) { + background: none; + border-color: transparent; + isolation: isolate; + + &::before { + content: ''; + position: absolute; + inset: -1px; + z-index: -1; + border-radius: inherit; + background: var(--tb-surface); + } + + &::after { + content: ''; + position: absolute; + inset: -7px; + z-index: -2; + border-radius: 50%; + background: var(--ai-glow); + filter: blur(10px); + pointer-events: none; + --ai-glow-peak: .5; + opacity: .35; + animation: ai-glow-breathe 2.4s ease-in-out infinite, ai-glow-turn 6s linear infinite; + } + } +} + +@keyframes ai-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 ai-glow-turn { + to { + rotate: 1turn; + } +} + +@media (prefers-reduced-motion: reduce) { + .k-pill:not(.new)::after { + animation: none; + } +} + +.k-notice { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 8px 8px 12px; + border-radius: 10px; + background: rgba(0, 0, 0, 0.035); + font: 400 13.5px/19px var(--tb-font); + color: var(--tb-ink-76); + + > span:not(.mat-icon) { + flex: 1; + min-width: 0; + } + + .mat-icon { + flex: none; + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-ink-54); + } + + &.warn { + background: var(--tb-caution-tint, #fff3e0); + + .mat-icon { + color: var(--tb-caution); + } + } + + &.blocking { + background: color-mix(in srgb, var(--tb-crit) 7%, transparent); + color: var(--tb-ink); + + .mat-icon { + color: var(--tb-crit); + } + } + + .mdc-button { + flex: none; + height: 30px; + } +} + +.k-notice-edge { + max-width: 760px; + margin: 0 auto 8px; +} + +a.tb-chiplink, a.tb-chiplink:hover, a.tb-chiplink:focus-visible { + text-decoration: none !important; + border-bottom: 0 !important; + color: inherit; + border-radius: 6px; +} + +a.tb-chiplink > code { + position: relative; + top: 0; + cursor: pointer; + transition: box-shadow .12s ease; +} + +a.tb-chiplink > code:not(.k-ent) { + 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; +} + +a.tb-chiplink > code.k-ent { + padding-right: 2px; +} + +code.k-ent > .tb-chip-go { + display: inline-block; + font-size: 14px; + width: 11px; + height: 14px; + line-height: 14px; + margin-left: 2px; + overflow: hidden; + text-indent: -1.5px; + vertical-align: -2px; + color: var(--tb-ink-38); + transition: color .12s ease; +} + +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); +} + +a.tb-chiplink:hover .tb-chip-go, a.tb-chiplink:focus-visible .tb-chip-go { + color: var(--ai-link); +} + +a.tb-chiplink:hover > code, a.tb-chiplink:focus-visible > code { + text-decoration-color: currentColor; +} + +a.tb-chiplink:active > code { + top: 1px; +} + +a.tb-chiplink:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; +} + +.tb-list { + min-width: 0; + font-family: var(--tb-font, Roboto, sans-serif); + + &[data-pal="device"] .tb-rec-tile { background: var(--entity-device-bg); color: var(--entity-device-fg); } + &[data-pal="path"] .tb-rec-tile { background: var(--entity-path-bg); color: var(--entity-path-fg); } + &[data-pal="chain"] .tb-rec-tile { background: var(--entity-chain-bg); color: var(--entity-chain-fg); } + &[data-pal="rule"] .tb-rec-tile { background: var(--entity-rule-bg); color: var(--entity-rule-fg); } + &[data-pal="view"] .tb-rec-tile { background: var(--entity-view-bg); color: var(--entity-view-fg); } + &[data-pal="people"] .tb-rec-tile { background: var(--entity-people-bg); color: var(--entity-people-fg); } + &[data-pal="solution"] .tb-rec-tile { background: var(--entity-solution-bg); color: var(--entity-solution-fg); } + + &.open .tb-list-chev { + transform: rotate(180deg); + } +} + +.tb-list-head { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + font: 400 14px/20px var(--tb-font); + color: var(--tb-ink); + text-align: left; + cursor: pointer; + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 2px; + } + + &:hover .mat-icon.tb-list-chev { + color: var(--tb-ink); + } +} + +.tb-list-label { + flex: none; + font-weight: 500; +} + +.tb-list .tb-list-head .mat-icon.tb-list-chev { + flex: none; + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; + color: var(--tb-ink-38); + transition: transform .15s ease, color .15s ease; +} + +.tb-list-head .tb-rec-tile { + font-size: 12px; + font-weight: 500; + letter-spacing: -.2px; + font-variant-numeric: tabular-nums; +} + +.tb-list-body { + margin: 2px 0 0 32px; + + > .tb-rec.line { + min-height: 32px; + padding: 4px 0; + border: 0; + border-radius: 0; + background: none; + } + + > .tb-rec.line { + width: fit-content; + max-width: 100%; + + .tb-rec-tile { + background: none; + } + + + .tb-rec.line { + border-top: 1px solid rgba(0, 0, 0, 0.06); + } + } +} + +.art-ib { + flex: none; + 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; + 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: 20px; + width: 20px; + height: 20px; + } +} + +.art-pane { + position: relative; + flex: 0 0 50%; + min-width: 360px; + max-width: calc(100% - var(--chat-col-min)); + display: flex; + flex-direction: column; + min-height: 0; + border-left: 1px solid var(--tb-line); + background: var(--tb-surface); + container: pane / inline-size; + animation: art-pane-in 280ms cubic-bezier(.05, .7, .1, 1) both; + transition: opacity .15s ease; + + &.closing { + opacity: .55; + } + + @media (prefers-reduced-motion: reduce) { + animation: none; + } + + --art-bg: var(--tb-surface); +} + +@keyframes art-pane-in { + from { + opacity: 0; + transform: translateX(24px); + } +} + +.art-pane-edge { + position: absolute; + top: 0; + bottom: 0; + left: -5px; + z-index: 4; + width: 10px; + cursor: ew-resize; + touch-action: none; + + &::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 4px; + width: 2px; + background: transparent; + transition: background-color .12s ease; + } + + &:hover::after, &:focus-visible::after { + background: var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + } + + &.held::after { + background: var(--ai-selected); + } + + &:focus-visible { + outline: 0; + } +} + +.art-pane-head { + position: relative; + z-index: 3; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + padding: 7px 16px; + box-sizing: border-box; + background: var(--tb-surface); + box-shadow: 0 1px 0 var(--tb-line); +} + +.art-pane-close { + margin-left: -6px; + + .narrow-only { + display: none; + } +} + +.art-pane-body { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-gutter: stable; + animation: art-view-in .22s ease; + + > * { + flex: none; + } + + &.dark { + overflow: hidden; + } +} + +@keyframes art-view-in { + from { + opacity: .4; + } +} + +.art-pane-foot { + position: relative; + flex: none; + display: flex; + align-items: center; + gap: 8px; + margin: 0; + padding: 10px var(--art-x, 16px); + border-top: 1px solid var(--tb-line); + background: var(--tb-surface); +} + +.art-tray { + position: absolute; + left: 50%; + bottom: calc(100% - 1px); + z-index: 2; + transform: translateX(-50%); + display: inline-flex; + align-items: center; + gap: 8px; + max-width: calc(100% - 40px); + padding: 6px 10px 7px 12px; + border: 0; + border-radius: 10px 10px 0 0; + background: var(--tb-ink); + color: var(--tb-surface); + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + cursor: pointer; + box-shadow: 0 -2px 10px rgba(16, 24, 40, 0.1); + animation: art-tray-in .22s cubic-bezier(.05, .7, .1, 1) both; + + > .mat-icon.mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--ai-mark-ink-dark); + } + + > .mat-icon.mat-icon.art-tray-chev { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + + b { + font-weight: 500; + white-space: nowrap; + } + + &:hover { + background: color-mix(in srgb, var(--tb-ink) 88%, var(--tb-surface)); + + .mat-icon.art-tray-chev { + color: var(--tb-surface); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + > .mat-icon.mat-icon.art-tray-chev { + color: color-mix(in srgb, var(--tb-surface) 55%, transparent); + } + + .art-tray-note.failed { + color: color-mix(in oklab, var(--tb-crit) 55%, var(--tb-surface)); + } + + tb-ai-spin { + --spin: 20px; + --spin-color: var(--ai-mark-ink-dark); + } +} + +@keyframes art-tray-in { + from { + transform: translate(-50%, 8px); + opacity: 0; + } +} + +.art-tray-note { + min-width: 0; + max-width: 320px; + display: inline-flex; + align-items: center; + gap: 8px; + color: color-mix(in srgb, var(--tb-surface) 72%, transparent); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + + &::before { + content: '·'; + color: color-mix(in srgb, var(--tb-surface) 40%, transparent); + } +} + +.art-tray-dot { + flex: none; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--tb-caution); +} + +@media (max-width: 1099px) { + .art-cols.with-pane { + position: relative; + + .art-pane { + position: absolute; + inset: 0; + z-index: 5; + min-width: 0; + max-width: none; + flex-basis: auto !important; + border-left: 0; + } + + .art-pane-edge { + display: none; + } + + .art-pane-close { + .wide-only { + display: none; + } + + .narrow-only { + display: inline-block; + } + } + } +} + +.art-pane-head::after, .art-pane-foot::before { + content: ''; + position: absolute; + left: 0; + right: 0; + height: 12px; + pointer-events: none; + opacity: 0; + transition: opacity .15s ease; +} + +.art-pane-head::after { + top: 100%; + opacity: .45; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); +} + +.art-pane-foot::before { + bottom: 100%; + background: linear-gradient(to top, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); +} + +.art-pane.scrolled .art-pane-head::after, .art-pane.more .art-pane-foot::before { + opacity: 1; +} + +.art-cols { + position: relative; + flex: 1; + min-height: 0; + display: flex; + container: art-cols / inline-size; +} + +@container art-cols (max-width: 1079px) { + .art-pane { + flex-basis: calc(100% - 380px); + } +} + +@container art-cols (min-width: 1617px) { + .art-pane { + flex-basis: calc(100% - var(--chat-col-max)); + } +} + +.art-cols.narrow.with-pane { + .art-pane { + position: absolute; + inset: 0; + z-index: 5; + min-width: 0; + max-width: none; + flex-basis: auto !important; + border-left: 0; + } + + .art-pane-edge { + display: none; + } + + .art-pane-close { + .wide-only { + display: none; + } + + .narrow-only { + display: inline-block; + } + } +} + +.art-pane.art-dark { + --art-bg: var(--tb-code-bg); + --k-grey: var(--tb-code-head-fg); + border-left-color: transparent; + background: var(--tb-code-bg); + color: var(--tb-code-fg); + + .art-pane-head { + background: var(--tb-code-bg); + box-shadow: none; + border-bottom: 1px solid var(--tb-code-line); + + &::after { + opacity: 0 !important; + } + } + + .art-title { + color: var(--tb-code-fg); + + > .mat-icon, small { + color: var(--tb-code-head-fg); + } + } + + .art-ib, .art-tool, .art-tool .mat-icon { + color: var(--tb-code-head-fg); + } + + .art-ib:hover, .art-tool:hover { + color: #fff; + background: rgba(255, 255, 255, 0.08); + } + + .art-tool:hover .mat-icon { + color: #fff; + } + + .art-tools .art-tool.on { + background: rgba(143, 227, 211, 0.12); + color: var(--ai-dark-accent); + + .mat-icon { + color: var(--ai-dark-accent); + } + } + + .art-tool.copied, .art-tool.copied .mat-icon { + color: var(--ai-dark-accent) !important; + } + + .art-pane-body { + scrollbar-color: rgba(255, 255, 255, 0.22) transparent; + } +} + +.art-pane-head h2.art-title { + flex: 1; + min-width: 0; + margin: 0; + display: flex; + align-items: center; + gap: 8px; + overflow: hidden; + white-space: nowrap; + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + font-weight: 500; + color: var(--tb-ink); + + > .mat-icon { + flex: none; + color: var(--tb-ink-54); + } + + > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + + small { + flex: none; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + font-weight: 400; + color: var(--k-grey); + } +} + +@container pane (max-width: 470px) { + .art-title small { + display: none; + } +} + +.art-head-r { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + margin-left: auto; +} + +.art-tools { + display: inline-flex; + align-items: center; + gap: 2px; +} + +.art-head-r > .art-tools + .art-tools { + margin-left: 8px; +} + +.art-tool { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + height: 30px; + 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; + + &.icon-only { + width: 30px; + padding: 0; + } + + .mat-icon { + color: var(--tb-ink-54); + } + + &:hover { + color: var(--tb-ink); + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + + .mat-icon { + color: var(--tb-ink); + } + } + + &.on { + background: color-mix(in srgb, var(--ai-action) 10%, transparent); + color: var(--ai-action); + + .mat-icon { + color: var(--ai-action); + } + } + + &.copied, &.copied .mat-icon { + color: var(--tb-ok) !important; + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.art-cards { + display: grid; + gap: 8px; + max-width: 480px; +} + +.art-card { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + padding: 8px 10px 8px 12px; + border: 1px solid var(--k-stroke); + border-radius: 10px; + background: var(--tb-surface); + font: inherit; + font-size: 14px; + line-height: 20px; + text-align: left; + color: var(--tb-ink); + cursor: pointer; + transition: border-color .15s ease, background-color .15s ease; + + &:hover { + border-color: var(--k-stroke-hover, rgba(0, 0, 0, 0.2)); + background: color-mix(in srgb, var(--tb-ink) 2%, transparent); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.on { + border-color: color-mix(in srgb, var(--ai-action) 45%, var(--k-stroke)); + background: var(--ai-selected-wash); + + .art-card-ic { + background: var(--ai-action); + color: var(--ai-on-action); + } + + .mat-icon.art-card-chev { + color: var(--ai-action); + } + } +} + +.art-card.made { + padding: 0; + cursor: default; + + .art-card-open { +flex: 1; +min-width: 0; +display: flex; +align-items: center; +gap: 12px; +margin: 0; +padding: 8px 4px 8px 12px; +border: 0; +border-radius: 10px 0 0 10px; +background: none; +font: inherit; +text-align: left; +color: inherit; +cursor: pointer; + +&:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: -2px; +} + } + + .art-card-dl { +flex: none; +display: inline-flex; +align-items: center; +justify-content: center; +width: 32px; +height: 32px; +margin: 0 8px 0 0; +padding: 0; +border: 0; +border-radius: 8px; +background: none; +color: var(--tb-ink-54); +cursor: pointer; + +&:hover { + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + color: var(--tb-ink); +} + +&:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; +} + } +} + +.art-card-ic { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 9px; + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + color: var(--tb-ink-76); +} + +.art-card-t { + flex: 1; + min-width: 0; + display: grid; + gap: 1px; + + b { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + } + + small { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-grey); + } + + small { + font-variant-numeric: tabular-nums; + } + + b .art-name { + display: block; + } +} + +.art-card .mat-icon.art-card-chev { + flex: none; + color: var(--tb-ink-38); +} + +.art-pane-body > tb-ai-file-body { + --art-x: 16px; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} + +.file-code, .file-edit { + --fc-ink: var(--tb-ink); + --fc-ln: var(--tb-ink-38); + --fc-ln-hover: var(--tb-ink-76); + --fc-row: color-mix(in srgb, var(--tb-ink) 3%, transparent); + --hl-cmd: #0b5f8a; + --hl-flag: #5c6b7a; + --hl-str: #8a4b08; + --hl-num: #6f3fb2; + --hl-key: #1d4ed8; + --hl-com: #7a8791; + --hl-err: #b42318; + --hl-fn: #3f6212; + --hl-bool: #a21caf; + --hl-lvl: #15803d; + flex: 1; + min-height: 0; + overflow: auto; + background: var(--art-bg); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + letter-spacing: .25px; + color: var(--fc-ink); + tab-size: 2; + + .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(--fc-ink); + } + + .hl-fn { + color: var(--hl-fn); + } + + .hl-bool { + color: var(--hl-bool); + } + + .hl-lvl { + color: var(--hl-lvl); + } +} + +.art-dark :is(.file-code, .file-edit) { + --fc-ink: var(--tb-code-fg); + --fc-ln: rgba(255, 255, 255, 0.32); + --fc-ln-hover: rgba(255, 255, 255, 0.72); + --fc-row: rgba(255, 255, 255, 0.04); + --hl-cmd: var(--ai-dark-accent); + --hl-flag: #9fb6c8; + --hl-str: #f2c98a; + --hl-num: #d4b4f7; + --hl-key: #9cc8f2; + --hl-com: #8a98a3; + --hl-err: #ff9d92; + --hl-fn: #d7e8a3; + --hl-bool: #f3b6d2; + --hl-lvl: #9bdda8; +} + +.file-lines { + min-width: max-content; + margin: 0; + padding: 12px 0 24px; + list-style: none; + + &:has(li:nth-child(1000)) { + --file-gutter: 68px; + } + + li { + display: grid; + grid-template-columns: var(--file-gutter, 56px) minmax(0, 1fr); + + &:hover { + background: var(--fc-row); + + .ln { + color: var(--fc-ln-hover); + background: color-mix(in srgb, var(--fc-row), var(--art-bg)); + } + } + + > code { + display: block; + padding: 0 var(--art-x) 0 0; + border: 0; + border-radius: 0; + background: none; + white-space: pre; + font: inherit; + color: inherit; + } + } + + .ln { + position: sticky; + left: 0; + z-index: 1; + display: block; + padding: 0 12px 0 0; + background: var(--art-bg); + letter-spacing: normal; + text-align: right; + color: var(--fc-ln); + user-select: none; + } + + .tb-line { + display: inline; + } + + .ln { + border: 0; + font: inherit; + cursor: pointer; + } + + li.marked, li.marked .ln { + background: color-mix(in srgb, var(--fc-mark), var(--art-bg)); + } + + li.marked .ln { + color: var(--fc-mark-ink); + box-shadow: inset -2px 0 0 var(--fc-mark-ink); + } + + mark.fm { + border-radius: 2px; + background: var(--fc-find); + color: inherit; + + &.now { + background: var(--fc-find-now); + box-shadow: 0 0 0 1px var(--fc-find-now); + } + } +} + +.file-code.wrap .file-lines { + min-width: 0; + + li > code { + white-space: pre-wrap; + word-break: normal; + overflow-wrap: break-word; + padding-left: calc(var(--ind, 0ch) + 2ch); + text-indent: calc(-1 * (var(--ind, 0ch) + 2ch)); + } +} + +.file-md { + width: 100%; + max-width: 760px; + margin: 0 auto; + padding: 20px var(--art-x) 40px; + box-sizing: border-box; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink); + + h1, h2, h3, h4, h5 { + margin: 28px 0 8px; + font-weight: 500; + letter-spacing: -0.1px; + color: var(--tb-ink); + } + + h1, h2 { + font-size: var(--chat-title); + line-height: var(--chat-title-lh); + letter-spacing: -0.3px; + } + + h3 { + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + } + + h4, h5 { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + p { + margin: 0 0 12px; + } + + ul, ol { + margin: 0 0 12px; + padding-left: 24px; + } + + li + li { + margin-top: 4px; + } + + pre { + margin: 0 0 16px; + padding: 12px 16px; + overflow: auto; + border-radius: 10px; + background: var(--tb-code-bg); + color: var(--tb-code-fg); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + + code { + padding: 0; + background: none; + color: inherit; + font: inherit; + } + } + + code { + padding: 1px 5px; + border-radius: 4px; + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + font-family: var(--tb-mono); + font-size: var(--chat-code); + } + + a { + color: var(--ai-link); + } + + table { + margin: 0 0 16px; + border-collapse: collapse; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + th, td { + padding: 6px 12px 6px 0; + border-bottom: 1px solid var(--tb-line); + text-align: left; + } + + th { + font-weight: 500; + } +} + +.agent.streaming [class*="tb-markdown-view"] > :is(p, h1, h2, h3, h4, h5, h6):last-child::after, +.agent.streaming [class*="tb-markdown-view"] > :is(ul, ol):last-child > li:last-child::after { + content: ''; + display: inline-block; + width: 2px; + height: 1em; + margin-left: 2px; + vertical-align: -2px; + background: var(--tb-ink); + animation: k-caret 1s steps(2, start) infinite; + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes k-caret { + to { + opacity: 0; + } +} + +.k-docs { + display: grid; + gap: 10px; +} + +.tb-rec.card.source { + max-width: 560px; + margin: 0; + + .tb-rec-tile { + background: var(--ai-teal-50); + color: var(--ai-teal-500); + } + + &.ext .tb-rec-tile { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink-60); + } + + .tb-open { + pointer-events: none; + } + + .tb-rec-det > q.tb-rec-note { + display: block; + font-size: 13.5px; + line-height: 19px; + quotes: '\201C' '\201D'; + } +} + +.agent-docs { + margin-top: 12px; +} + +.ai .agent .agent-body .tb-markdown-view [class*="tb-markdown-view-"] .k-hint.agent-hint { + margin: 10px 0 0; + font-size: 14px; + line-height: 20px; + color: var(--k-grey); + + b { + font-size: inherit; + line-height: inherit; + font-weight: 500; + color: var(--tb-ink); + } +} + +.composer-ghost { + position: absolute; + top: 12px; + left: 42px; + right: 58px; + overflow: hidden; + overflow-wrap: break-word; + pointer-events: none; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--k-faint); + + kbd { + @include tb-ai-kbd; + margin-left: 10px; + background: none; + color: inherit; + font-weight: 400; + vertical-align: 1px; + } +} + +.tb-ai-sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.file-code { + --fc-ws: rgba(0, 0, 0, 0.34); + --fc-trail: rgba(180, 35, 24, 0.12); + --fc-mark: color-mix(in srgb, var(--ai-selected) 14%, transparent); + --fc-mark-ink: var(--ai-action); + --fc-find: rgba(234, 179, 8, 0.28); + --fc-find-now: rgba(234, 179, 8, 0.62); +} + +.art-dark .file-code { + --fc-ws: rgba(255, 255, 255, 0.36); + --fc-trail: rgba(255, 157, 146, 0.2); + --fc-mark: rgba(143, 227, 211, 0.1); + --fc-mark-ink: var(--hl-cmd); + --fc-find: rgba(250, 204, 21, 0.22); + --fc-find-now: rgba(250, 204, 21, 0.55); +} + +.file-code.ws .ws { + position: relative; + + &::before { + content: '·'; + position: absolute; + left: 0; + right: 0; + text-align: center; + color: var(--fc-ws); + pointer-events: none; + } + + &.tab::before { + content: '→'; + } + + &.quiet::before { + content: none; + } + + &.trail { + background: var(--fc-trail); + } +} + +.file-find { + flex: none; + display: flex; + align-items: center; + gap: 6px; + height: 48px; + padding: 0 8px 0 12px; + border-bottom: 1px solid var(--k-stroke); + background: var(--art-bg); + box-sizing: border-box; +} + +.art-dark .file-find { + border-bottom-color: var(--tb-code-line); +} + +.file-find-ic { + color: var(--tb-ink-54); +} + +.file-find-in { + flex: 1; + min-width: 0; + height: 28px; + padding: 0 4px; + border: 0; + outline: 0; + background: none; + font-family: var(--tb-mono); + font-size: var(--chat-code); + color: var(--tb-ink); + + &::placeholder { + font-family: var(--tb-font); + color: var(--tb-ink-38); + } + + &::-webkit-search-cancel-button { + -webkit-appearance: none; + } +} + +.file-find-b { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + 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); + } +} + +.art-dark { + .file-find-ic, .file-find-n, .file-find-b { + color: rgba(255, 255, 255, 0.72); + } + + .file-find-in { + color: var(--tb-code-fg); + + &::placeholder { + color: rgba(255, 255, 255, 0.32); + } + } + + .file-find-b:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + .file-bar-info { + color: var(--tb-code-head-fg); + } + + .file-bar-sep { + color: rgba(255, 255, 255, 0.28); + } + + .file-bar-state { + color: var(--tb-code-fg); + } + + :is(.file-bar-saved, .file-bar-ed) { + color: var(--ai-dark-accent); + } + + .file-bar-acts .mdc-button.file-bar-save:not(:disabled) { + background: var(--ai-dark-accent); + color: var(--tb-code-bg); + + &:hover { + background: var(--ai-dark-accent-hover); + } + } +} + +.art-spacer { + flex: 1; +} + +.file-marked { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--tb-ink-76); + + .mat-icon { + color: var(--ai-action); + } +} + +.art-pane-foot .file-marked { + white-space: nowrap; + + gap: 8px; + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--k-grey); +} + +.art-dark .art-pane-foot .mdc-button.mat-mdc-outlined-button { + background: transparent; + border-color: rgba(255, 255, 255, 0.24); + color: var(--tb-code-fg); + + .mat-icon { + color: inherit; + } +} + +.art-dark .art-pane-foot .mdc-button.mat-mdc-button { + color: var(--tb-code-fg); +} + +.art-dark .art-pane-foot { + border-top-color: var(--tb-code-line); + background: var(--tb-code-bg); + color: var(--tb-code-fg); + + .file-marked, .file-marked .mat-icon { + color: var(--tb-code-head-fg); + } + + .mdc-button:not(.mat-mdc-unelevated-button) { + --mat-button-text-label-text-color: var(--tb-code-fg); + --mat-button-outlined-label-text-color: var(--tb-code-fg); + --mat-button-outlined-outline-color: rgba(255, 255, 255, 0.24); + } + + .art-ask { + --mat-button-filled-container-color: var(--ai-dark-accent); + --mat-button-filled-label-text-color: var(--tb-code-bg); + } +} + +.art-opts { + min-width: 240px; + + .art-opt-l { + flex: 1; + } + + .mat-mdc-menu-item .mat-mdc-menu-item-text { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + } +} + +.art-switch { + position: relative; + flex: none; + margin-left: auto; + width: 30px; + height: 18px; + border-radius: 9px; + background: color-mix(in srgb, var(--tb-ink) 24%, transparent); + transition: background-color .15s ease; + + i { + position: absolute; + top: 2px; + left: 2px; + width: 14px; + height: 14px; + border-radius: 50%; + background: #fff; + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.24); + transition: transform .15s cubic-bezier(.2, 0, 0, 1); + } + + &.on { + background: var(--ai-action); + + i { + transform: translateX(12px); + } + } +} + +.art-opt-row { + display: flex; + align-items: center; + gap: 10px; + min-height: 40px; + padding: 0 8px 0 16px; + font: 400 13.5px/20px var(--tb-font); + color: var(--tb-ink); + + > .mat-icon { + flex: none; + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; + color: var(--tb-ink-60); + } + + > span { + flex: 1; + } +} + +.art-modes { + flex: none; + display: inline-flex; + gap: 2px; + padding: 2px; + border-radius: 9px; + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + + button { + display: inline-flex; + align-items: center; + gap: 5px; + height: 26px; + padding: 0 8px 0 6px; + border: 0; + border-radius: 7px; + background: none; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + + .mat-icon { + color: inherit; + } + + &:hover { + color: var(--tb-ink); + } + + &[aria-checked="true"] { + background: var(--tb-surface); + color: var(--tb-ink); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.12), 0 0 0 1px rgba(16, 24, 40, 0.04); + cursor: default; + } + } +} + +.k-quote-chip { + display: inline-flex; + align-items: center; + gap: 8px; + align-self: flex-end; + max-width: 100%; + margin-bottom: 6px; + padding: 6px 12px 6px 10px; + border: 1px solid var(--k-stroke); + border-radius: 10px; + background: var(--tb-surface); + font-size: 13px; + line-height: 18px; + + > .mat-icon { + flex: none; + color: var(--tb-ink-54); + } + + > span { + display: grid; + min-width: 0; + } + + b { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 500; + color: var(--tb-ink); + } + + small { + font-size: 12px; + line-height: 16px; + color: var(--k-grey); + } +} + +.k-optrow { + display: flex; + flex-wrap: wrap; + gap: 8px; + + .ob-chip { + height: calc(var(--chat-control) + 2px); + padding: 0 14px; + font-size: var(--chat-line); + line-height: var(--chat-control); + + &[aria-pressed="true"] { + border-color: var(--ai-selected); + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--ai-selected); + font-weight: 500; + color: var(--tb-ink); + } + } +} + +.k-ask .k-swatch { + display: inline-block; + flex: none; + width: 16px; + height: 16px; + margin-right: 2px; + border-radius: 50%; + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.16); + vertical-align: -3px; +} + +.k-ask .k-optbody b .k-swatch { + margin-right: 8px; +} + +.k-ask .k-opthint { + margin: 8px 0 0; + font-size: 14px; + line-height: 19px; + letter-spacing: .25px; + color: var(--k-grey); + + &::first-letter { + text-transform: uppercase; + } +} + +.k-ask .k-other-area { + display: block; + width: 100%; + margin-top: 8px; +} + +.k-ask.sheet { + gap: 0; + + > .k-head + .k-sheet-q { + margin-top: 12px; + } + + > .k-actions { + padding-top: 14px; + border-top: 1px solid var(--tb-line); + } + + .k-ask-q b { + font-size: 15px; + line-height: 21px; + } + + .k-optcard { + padding: 8px 10px; + } +} + +.k-sheet-q { + display: grid; + gap: 12px; + padding: 14px 0 16px; + border-top: 1px solid rgba(0, 0, 0, 0.07); +} + +.k-ask-q.numbered { + display: grid; + grid-template-columns: 28px minmax(0, 1fr); + column-gap: 10px; + align-items: center; + + > b, > .k-why { + grid-column: 2; + } +} + +.k-qn { + grid-row: 1; + justify-self: start; + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 22px; + height: 22px; + padding: 0; + box-sizing: border-box; + border-radius: 11px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1.5px var(--ai-teal-500); + gap: 1px; + font: 500 12px/22px var(--tb-font); + letter-spacing: normal; + white-space: nowrap; + color: var(--tb-ink-76); + + b { + font-weight: 600; + line-height: 22px; + } +} + +.k-tel { + display: inline-flex; + align-items: center; + gap: 4px; + font-family: var(--tb-mono); + font-size: var(--chat-chip, 14px); + line-height: var(--chat-text-lh); + white-space: nowrap; + vertical-align: baseline; + + code.k-tel-key.k-tel-key { + padding: var(--chat-chip-pad, 1px) 7px; + border: 0; + 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); + color: var(--tb-ink); + } + + .k-tel-val { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 1px 4px; + border-radius: 5px; + font-size: var(--chat-chip-mono, 14px); + line-height: var(--chat-chip-lh); + font-weight: 600; + font-variant-numeric: tabular-nums; + color: var(--tb-ink); + } + + .k-tel-unit { + margin-left: -1px; + font-weight: 400; + color: var(--k-grey); + } +} + +.tb-ai-composer.docked .composer-ghost { + top: 10px; + left: 33px; + right: 44px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); +} + +.k-hood { + display: flex; + gap: 8px; + align-items: flex-start; + margin: 8px 0 0; + font-family: var(--tb-mono); + font-size: 12.5px; + line-height: 18px; + color: var(--k-grey); + overflow-wrap: anywhere; + + .mat-icon { + flex: none; + margin-top: 1px; + color: var(--tb-ink-38); + } +} + +.tb-hub-ic { + display: inline-flex; + vertical-align: -3px; + margin-right: 1px; + color: var(--tb-ink-54); + + .mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + } +} + +.tb-rec-meta .mat-icon.k-ver { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + margin-left: 3px; + vertical-align: -3px; + color: var(--tb-primary-500); +} + +tb-ai-action-detail.k-detail { + display: block; + font-family: var(--tb-font); + + .k-detail-recs, + .k-tels, + .k-series, + .k-made, + .k-detail-links, + .k-detail-facts { + max-height: 214px; + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-color: var(--tb-ink-38) transparent; + } + + .k-detail-recs { + width: fit-content; + max-width: 100%; + box-sizing: border-box; + padding-right: 6px; + } + + > :first-child { + margin-top: 0; + } + + .k-detail-label { + margin: 12px 0 6px; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + font-weight: 500; + color: var(--tb-text-secondary); + } + + .k-detail-recs { + display: grid; + justify-items: start; + gap: 6px; + margin-top: 10px; + + .tb-rec { + margin: 0; + max-width: 100%; + } + } + + .k-detail-label + .k-detail-recs, + .k-detail-label + .k-tels, + .k-detail-label + .k-made { + margin-top: 0; + } + + .k-detail-images { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin: 4px 0; + + figure { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; + margin: 0; + } + + img { + display: block; + max-width: 160px; + max-height: 64px; + min-width: 24px; + min-height: 24px; + padding: 6px; + box-sizing: content-box; + object-fit: contain; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + } + + figcaption { + font-size: 12px; + line-height: 16px; + color: var(--k-grey); + } + } + + .k-detail-more, + .k-detail-note { + margin: 8px 0 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); + } + + .k-tels { + display: flex; + flex-wrap: wrap; + gap: 6px 12px; + margin-top: 10px; + + > code.k-tel-key { + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: 13px; + line-height: 20px; + color: var(--tb-ink); + } + + .k-tel { + font-size: 13px; + white-space: normal; + overflow-wrap: anywhere; + + code.k-tel-key.k-tel-key, .k-tel-val { + font-size: 13px; + line-height: 20px; + } + } + } + + .k-series { + display: grid; + gap: 6px; + margin-top: 10px; + } + + .k-series-row { + display: grid; + grid-template-columns: max-content 96px minmax(0, 1fr); + align-items: center; + gap: 10px; + + code.k-tel-key { + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: 13px; + line-height: 20px; + color: var(--tb-ink); + } + } + + .k-series-spark { + width: 96px; + height: 20px; + overflow: visible; + + path { + fill: none; + stroke: var(--ai-teal-500); + stroke-width: 1.5; + stroke-linejoin: round; + vector-effect: non-scaling-stroke; + } + } + + .k-series-meta { + font-family: var(--tb-mono); + font-size: 12px; + line-height: 18px; + color: var(--k-grey); + font-variant-numeric: tabular-nums; + } + + .k-detail-facts { + margin-top: 10px; + gap: 4px 14px; + font-size: 13px; + line-height: 20px; + + dd.mono { + font-family: var(--tb-mono); + font-size: 12.5px; + } + + dd a { + color: var(--tb-ink); + text-decoration: underline; + text-decoration-color: var(--tb-ink-38); + text-underline-offset: 3px; + } + } + + .k-reveal { + display: inline-flex; + vertical-align: -3px; + margin-left: 6px; + padding: 0; + border: 0; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + color: var(--tb-ink); + } + } + + .k-made { + margin: 10px 0 0; + padding-left: 18px; + font-size: 13px; + line-height: 20px; + color: var(--k-grey); + } + + .tb-codeblock { + margin-top: 6px; + max-width: 100%; + } + + .k-detail-links { + display: grid; + gap: 10px; + margin-top: 10px; + } + + .k-detail-link { + display: grid; + gap: 1px; + text-decoration: none; + color: inherit; + + &:hover .k-detail-link-t { + text-decoration: underline; + } + } + + .k-detail-link-t { + font-size: 13.5px; + line-height: 20px; + font-weight: 500; + color: var(--ai-link, var(--tb-ink)); + } + + .k-detail-link-from { + font-size: 12px; + line-height: 16px; + color: var(--k-faint); + } + + .k-detail-link-s { + font-size: 12.5px; + line-height: 18px; + color: var(--k-grey); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + } + + .k-detail-md { + margin-top: 10px; + max-height: 320px; + overflow: auto; + box-sizing: border-box; + padding: 10px 14px; + border-radius: 10px; + background: color-mix(in srgb, var(--tb-ink) 3%, transparent); + box-shadow: inset 0 0 0 1px var(--tb-line); + font-size: 13px; + line-height: 20px; + color: var(--tb-ink-76); + overflow-wrap: anywhere; + scrollbar-width: thin; + scrollbar-color: var(--tb-ink-38) transparent; + + p, ul, ol, li, blockquote, table { + margin: 0 0 6px; + padding-left: 0; + padding-right: 0; + font-size: 13px; + line-height: 20px; + } + + ul, ol { + padding-left: 20px; + } + + li { + margin: 0 0 2px; + } + + h1, h2, h3, h4, h5, h6 { + margin: 12px 0 4px; + padding: 0; + font-size: 13px; + line-height: 20px; + font-weight: 600; + color: var(--tb-ink); + + &:first-child { + margin-top: 0; + } + } + + pre { + margin: 0 0 6px; + padding: 8px 10px; + border-radius: 6px; + font-size: 12px; + line-height: 18px; + white-space: pre-wrap; + } + + hr { + margin: 8px 0; + border: 0; + border-top: 1px solid var(--tb-line); + } + + img { + display: none; + } + } + + .k-detail-text { + margin: 10px 0 0; + font-size: 13px; + line-height: 20px; + color: var(--k-grey); + white-space: pre-wrap; + overflow-wrap: anywhere; + } + + .k-detail-json { + margin: 0; + max-height: 240px; + overflow: auto; + padding: 8px 10px; + border-radius: 8px; + background: var(--tb-line-soft); + font-family: var(--tb-mono); + font-size: 12px; + line-height: 18px; + white-space: pre-wrap; + overflow-wrap: anywhere; + color: var(--tb-ink-76); + } +} + +.art-files-ic { + flex: none; + display: inline-flex; + width: 20px; + height: 20px; + + svg { + width: 100%; + height: 100%; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; + } +} + +.art-files-n { + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + font-variant-numeric: tabular-nums; + color: inherit; +} + +.mat-mdc-menu-panel.tb-ai-chat-menu.art-list { + min-width: 280px; + max-width: min(400px, calc(100vw - 32px)); + max-height: min(420px, 70vh); + overscroll-behavior: contain; + + .tb-ai-menu-h.art-list-h { + padding: 8px 12px 6px; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + } + + .art-list-row { + position: relative; + } + + .art-list-row + .art-list-row { + margin-top: 2px; + } + + .mat-mdc-menu-item.art-list-item { + min-height: 40px; + padding: 4px 44px 4px 6px; + gap: 10px; + + .mat-mdc-menu-item-text { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + flex: 1; + } + + &.on { + background: var(--ai-selected-wash); + } + } + + .art-list-ic { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + + .mat-icon { + margin: 0; + color: var(--tb-ink-76); + } + } + + .art-list-item.on .art-list-ic { + background: var(--ai-action); + + .mat-icon { + color: var(--ai-on-action); + } + } + + .art-list-t { + flex: 1; + min-width: 0; + display: block; + + b { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + } + } + + .mat-icon.art-list-check { + margin: 0; + color: var(--ai-action); + } + + .art-list-del { + position: absolute; + top: 50%; + right: 6px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + opacity: 0; + transform: translateY(-50%); + transition: opacity .12s ease, background-color .12s ease, color .12s ease; + + .mat-icon { + color: inherit; + } + + &:hover { + background: color-mix(in srgb, var(--tb-ink) 8%, transparent); + color: var(--tb-ink); + } + } + + .art-list-row:is(:hover, :focus-within) { + .art-list-del { + opacity: 1; + } + + .art-list-check { + visibility: hidden; + } + } + + .art-list-confirm { + display: flex; + align-items: center; + gap: 8px; + min-height: 40px; + margin: 0 4px; + padding: 4px; + box-sizing: border-box; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + animation: art-view-in .16s ease; + } + + .art-list-q { + flex: 1; + min-width: 0; + display: grid; + + b { + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font: 400 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + color: var(--k-grey); + } + + .art-name { + display: inline; + } + } + + .art-list-no, .art-list-yes { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .12s ease, color .12s ease; + + .mat-icon { + color: inherit; + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } + + .art-list-no:hover { + background: color-mix(in srgb, var(--tb-ink) 8%, transparent); + color: var(--tb-ink); + } + + .art-list-yes { + background: var(--tb-surface); + color: var(--tb-ink); + box-shadow: 0 0 0 1px var(--k-stroke); + + &:hover { + color: var(--tb-crit); + box-shadow: 0 0 0 1px color-mix(in srgb, var(--tb-crit) 40%, transparent); + } + } + + @media (prefers-reduced-motion: reduce) { + .art-list-del { + transition: none; + } + + .art-list-confirm { + animation: none; + } + } +} + +.art-name { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.art-ext { + font-weight: 400; + color: var(--tb-ink-54); +} + +.art-dark .art-ext { + color: var(--tb-code-head-fg); +} + +.art-pane-head h2.art-title .art-name { + display: block; +} + +.art-card-ed { + margin-left: 6px; + font-weight: 500; + color: var(--ai-action); + + &::before { + content: '·'; + margin-right: 6px; + font-weight: 400; + color: var(--k-grey); + } +} + +.art-chip { + display: inline-flex; + align-items: center; + gap: 5px; + max-width: 100%; + height: 24px; + padding: 0 8px 0 6px; + box-sizing: border-box; + border: 1px solid var(--k-stroke); + border-radius: 6px; + background: var(--tb-surface); + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + vertical-align: middle; + cursor: pointer; + transition: border-color .15s ease, background-color .15s ease; + + > .mat-icon { + flex: none; + font-size: 16px; + width: 16px; + height: 16px; + color: var(--tb-ink-54); + } + + &:hover { + border-color: var(--k-stroke-hover); + background: color-mix(in srgb, var(--tb-ink) 2%, transparent); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.on { + border-color: color-mix(in srgb, var(--ai-action) 45%, var(--k-stroke)); + background: var(--ai-selected-wash); + + > .mat-icon { + color: var(--ai-action); + } + } +} + +.art-pane-foot.file-bar { + min-height: 48px; + padding: 6px var(--art-x, 16px); + gap: 12px; + box-sizing: border-box; + flex-wrap: nowrap; +} + +.file-bar-info { + flex: 1 1 auto; + min-width: 0; + display: flex; + align-items: center; + gap: 6px; + overflow: hidden; + white-space: nowrap; + font: 400 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + font-variant-numeric: tabular-nums; + color: var(--k-grey); + + .mat-icon { + flex: none; + font-size: 16px; + width: 16px; + height: 16px; + color: inherit; + } +} + +.file-bar-sep { + font-style: normal; + color: var(--tb-ink-38); +} + +.file-bar-state { + display: inline-flex; + align-items: center; + gap: 6px; + font-weight: 500; + color: var(--tb-ink-76); +} + +.file-bar-dot { + flex: none; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--tb-caution); +} + +.file-bar-saved { + display: inline-flex; + align-items: center; + gap: 4px; + font-weight: 500; + color: var(--tb-ok-text); + animation: art-copied-in .18s ease; +} + +.file-bar-ed { + font-weight: 500; + color: var(--ai-action); +} + +.file-bar-pos { + overflow: hidden; + text-overflow: ellipsis; +} + +.file-bar-acts { + flex: none; + display: flex; + align-items: center; + gap: 8px; + margin-left: auto; + + .mdc-button.file-bar-b { + height: 36px; + } + + .mdc-button.file-bar-save:not(:disabled) { + background: var(--ai-action); + color: var(--ai-on-action); + + &:hover { + background: color-mix(in srgb, var(--ai-action) 88%, var(--tb-ink)); + } + } +} + +@container pane (max-width: 470px) { + .file-bar :is(.file-bar-pos, .file-bar-sep:has(+ .file-bar-pos)) { + display: none; + } +} + +@keyframes art-copied-in { + from { + opacity: 0; + transform: translateY(2px); + } +} + +.file-edit { + position: relative; + flex: 1; + min-height: 0; + overflow: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + display: grid; + grid-template-columns: var(--file-gutter, 56px) minmax(0, 1fr); + align-items: start; + background: var(--art-bg); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + color: var(--fc-ink, var(--tb-ink)); + cursor: text; + + &:has(.file-edit-ln li:nth-child(1000)) { + --file-gutter: 68px; + } +} + +.file-edit-ln { + position: sticky; + left: 0; + z-index: 2; + margin: 0; + padding: 12px 12px 24px 0; + list-style: none; + text-align: right; + background: var(--art-bg); + color: var(--fc-ln, var(--tb-ink-38)); + user-select: none; + + li { + overflow: hidden; + } + + li.now { + color: var(--fc-ln-hover, var(--tb-ink-60)); + } +} + +.file-edit-in { + position: relative; + min-width: 0; +} + +.file-edit-hl, .file-edit-ta { + box-sizing: border-box; + margin: 0; + padding: 12px var(--art-x, 16px) 24px 0; + font: inherit; + letter-spacing: .25px; + tab-size: 2; + word-break: normal; +} + +.file-edit.wrap :is(.file-edit-hl, .file-edit-ta) { + white-space: pre-wrap; + overflow-wrap: break-word; +} + +.file-edit:not(.wrap) :is(.file-edit-hl, .file-edit-ta) { + white-space: pre; + overflow-wrap: normal; +} + +.file-edit-hl { + position: absolute; + top: 0; + left: 0; + right: 0; + pointer-events: none; + color: var(--fc-ink, var(--tb-ink)); +} + +.file-edit:not(.wrap) .file-edit-hl { + right: auto; + width: max-content; + min-width: 100%; +} + +.file-edit-row { + min-height: var(--chat-code-lh); + + .tb-line { + display: inline; + } +} + +.file-edit-ta { + position: relative; + z-index: 1; + display: block; + width: 100%; + min-height: 100%; + border: 0; + border-radius: 0; + outline: 0; + resize: none; + overflow: hidden; + background: none; + color: transparent; + -webkit-text-fill-color: transparent; + caret-color: var(--ai-action); + + &::selection { + background: color-mix(in srgb, var(--ai-selected) 24%, transparent); + } +} + +.art-dark .file-edit-ta { + caret-color: var(--ai-dark-accent); + + &::selection { + background: rgba(143, 227, 211, 0.24); + } +} + +.file-edit:not(.wrap) .file-edit-ta { + width: max-content; + min-width: 100%; +} + +.file-find-field { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 6px; + height: 32px; + margin-right: 6px; + padding: 0 4px 0 8px; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + box-shadow: inset 0 0 0 1px transparent; + cursor: text; + transition: box-shadow .12s ease, background-color .12s ease; + + &:focus-within { + background: var(--art-bg); + box-shadow: inset 0 0 0 1.5px var(--ai-focus); + } +} + +.art-dark .file-find-field { + background: rgba(255, 255, 255, 0.06); + + &:focus-within { + background: rgba(255, 255, 255, 0.03); + box-shadow: inset 0 0 0 1.5px var(--ai-dark-accent); + } +} + +.file-find-n { + flex: none; + white-space: nowrap; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-grey); + display: inline-flex; + align-items: center; + gap: 3px; + height: 22px; + padding: 0 8px; + border-radius: 11px; + background: color-mix(in srgb, var(--tb-ink) 7%, transparent); + + b { + font-weight: 600; + color: var(--fc-ink, var(--tb-ink)); + } + + span { + color: var(--fc-ln-hover, var(--k-grey)); + } + + &.none { + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + color: var(--tb-crit); + } +} + +.art-dark .file-find-n { + background: rgba(255, 255, 255, 0.08); + + b { + color: var(--tb-code-fg); + } + + span { + color: var(--tb-code-head-fg); + } + + &.none { + background: rgba(255, 157, 146, 0.14); + color: #ffb4ab; + } +} + +.file-find-sep { + flex: none; + width: 1px; + height: 18px; + margin: 0 4px; + background: var(--k-stroke); +} + +.file-marked-n { + display: inline-flex; + align-items: center; + height: 24px; + padding: 0 9px; + border-radius: 12px; + background: color-mix(in srgb, var(--ai-action) 10%, transparent); + color: var(--ai-action); + font-weight: 500; + font-variant-numeric: tabular-nums; +} + +.art-dark .file-marked-n { + background: rgba(143, 227, 211, 0.12); + color: var(--ai-dark-accent); +} + +.art-dark .art-pane-foot.art-marks .mdc-button.mat-mdc-button { + border-color: transparent; +} + +.art-pane-foot.art-marks .mdc-button { + height: 32px; +} + +.file-svg { + flex: 1; + display: flex; + align-items: flex-start; + justify-content: center; + min-height: 280px; + padding: 32px var(--art-x, 16px); + box-sizing: border-box; + background-color: var(--art-bg); + background-image: radial-gradient(color-mix(in srgb, var(--tb-ink) 12%, transparent) 1px, transparent 1.2px); + background-size: 16px 16px; + + .file-img-open { + display: block; + max-width: 100%; + padding: 0; + border: 0; + background: none; + cursor: zoom-in; + } +} + +.file-svg-img { + display: block; + max-width: 100%; + height: auto; + border-radius: 4px; + background: #fff; + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.06), 0 4px 16px rgba(16, 24, 40, 0.08); +} + +.file-svg-err { + display: flex; + align-items: center; + gap: 8px; + margin: 0; + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--k-grey); +} + +.art-tool.art-copy { + position: relative; + overflow: visible; + + .art-copy-ok { + position: absolute; + inset: 0; + margin: auto; + width: 18px; + height: 18px; + fill: none; + stroke: currentColor; + stroke-width: 2.2; + stroke-linecap: round; + stroke-linejoin: round; + stroke-dasharray: 22; + stroke-dashoffset: 22; + opacity: 0; + pointer-events: none; + } + + .art-copy-ic { + transition: transform .2s ease, opacity .2s ease; + } + + &.copied { + color: var(--tb-ok-text); + background: color-mix(in srgb, var(--tb-ok, #2e7d32) 10%, transparent); + + .art-copy-ic { + opacity: 0; + transform: rotate(-30deg) scale(.4); + } + + .art-copy-ok { + opacity: 1; + animation: art-check-draw .34s ease forwards; + } + + &::after { + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: 0 0 0 0 color-mix(in srgb, var(--tb-ok, #2e7d32) 45%, transparent); + animation: art-check-ring .6s ease-out; + pointer-events: none; + } + } +} + +.art-dark .art-tool.art-copy.copied { + color: var(--ai-dark-accent); + background: rgba(143, 227, 211, 0.12); +} + +@keyframes art-check-draw { + to { + stroke-dashoffset: 0; + } +} + +@keyframes art-check-ring { + to { + box-shadow: 0 0 0 8px transparent; + } +} + +@media (prefers-reduced-motion: reduce) { + .art-tool.art-copy { + .art-copy-ic { + transition: none; + } + + &.copied { + .art-copy-ok { + animation: none; + stroke-dashoffset: 0; + } + + &::after { + animation: none; + } + } + } + + .file-bar-saved { + animation: none; + } +} + +.tb-ai-keys-dialog .mat-mdc-dialog-surface { + width: min(calc(100vw - 32px), 640px); +} + +.k-keys-dialog, .k-keys-dialog.mat-mdc-dialog-component-host { + display: block; + max-height: calc(100vh - 32px); + box-sizing: border-box; + padding: 20px 24px 24px; + overflow: auto; + overscroll-behavior: contain; + + .k-keys-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 16px; + + h2.mat-mdc-dialog-title { + margin: 0; + padding: 0; + font: 500 var(--chat-title, 20px)/var(--chat-title-lh, 28px) var(--tb-font); + color: var(--tb-ink); + + &::before { + display: none; + } + } + } + + .k-keys-x { + flex: none; + margin: -4px -8px -4px 0; + color: var(--tb-ink-54); + } + + .k-keys-groups { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 24px 40px; + + h3 { + margin: 0 0 4px; + font: 500 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + color: var(--tb-ink-54); + } + } + + .k-keyrow { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 36px; + gap: 16px; + border-top: 1px solid rgba(0, 0, 0, 0.06); + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + + > span:first-child { + min-width: 0; + padding: 6px 0; + } + } + + h3 + .k-keyrow { + border-top: 0; + } + + .k-keys-sets { + flex: none; + display: inline-flex; + align-items: center; + gap: 10px; + } + + .tip-caps { + display: inline-flex; + gap: 4px; + } + + kbd { + @include tb-ai-kbd; + vertical-align: 0; + } + + @media (max-width: 599px) { + padding: 16px 16px 20px; + + .k-keys-groups { + grid-template-columns: minmax(0, 1fr); + } + } +} + +.file-bar-name { + font-weight: 500; + color: var(--tb-ink-76); +} + +.art-dark .file-bar-name { + color: var(--tb-code-fg); +} + +.file-bar-state.sol-json-err { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + color: var(--tb-crit); + + .file-bar-dot { + background: var(--tb-crit); + } +} + +.art-dark .file-bar-state.sol-json-err { + color: #ffb4ab; +} + +.sol-json-tools { + margin-left: auto; +} + +.ai-chat-loading { + flex: 1 0 auto; + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + width: 100%; + min-height: 160px; + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-54); + animation: ai-chat-loading-in .2s ease .25s both; + + tb-ai-spin { + --spin: 22px; + } + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes ai-chat-loading-in { + from { + opacity: 0; + } +} + +@keyframes tb-wait-pulse { + 0%, 100% { opacity: 1; transform: scale(1); } + 50% { opacity: .35; transform: scale(.7); } +} + +@media (prefers-reduced-motion: reduce) { + .tb-rec .tb-ai-state.wait i { + animation: none; + } +} + +.tb-list-head.static { + cursor: default; +} + +.tb-ai-disclosure { + display: block; +} + +tb-ai-records { + display: block; + margin-top: 14px; + + .tb-rec.card { + margin-top: 0; + } +} + +tb-ai-record-card { + display: block; +} + +.k-out-recs { + margin: 6px 0 0 28px; +} + +.tb-disc-section { + margin-top: 10px; + padding-left: 22px; + + > summary { + margin-left: -22px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink-76); + } + + > :not(summary) { + margin-top: 10px; + } +} + +.tb-disc-divided { + margin-top: 12px; + padding-left: 0; + border-top: 1px solid var(--tb-line); + + + .tb-disc-divided { + margin-top: 0; + } + + > summary { + margin-left: 0; + min-height: 44px; + width: auto; + font-size: 15px; + line-height: 22px; + color: var(--tb-ink); + } + + > :not(summary) { + margin-top: 2px; + } + + > :last-child { + margin-bottom: 16px; + } +} + +@container k-chat (max-width: 420px) { + .tb-ai-facts { + grid-template-columns: minmax(0, 1fr); + gap: 0; + + dd { + margin-bottom: 6px; + + &:last-child { + margin-bottom: 0; + } + } + } +} + +@container pane (max-width: 470px) { + .tb-ai-facts { + grid-template-columns: minmax(0, 1fr); + gap: 0; + + dd { + margin-bottom: 6px; + + &:last-child { + margin-bottom: 0; + } + } + } +} + +.tb-rec.card > .tb-rec-row > .tb-rec-tile { + margin-right: 12px; +} + +tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { + width: auto; + max-height: none; + overflow: visible; + padding-right: 0; + margin-left: 24px; + + > .tb-ai-more { + justify-self: start; + } + + grid-template-columns: minmax(0, 1fr); + gap: 0; + + .tb-rec.line { + width: fit-content; + max-width: 100%; + } +} + +.tb-rec.card.tight .tb-rec-pic { + &.wide, &.sq { + width: auto; + } +} + +@container k-col (max-width: 420px) { + .tb-rec.card { + padding: 8px 10px 10px; + + .tb-rec-row { + align-items: start; + } + + .tb-rec-tile { + width: 36px; + height: 36px; + border-radius: 9px; + + .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + } + } + + .tb-rec-det { + margin: 8px -10px -10px; + padding: 8px 10px 10px; + } + + .tb-rec-meta { + white-space: normal; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + } + + &.primary:not(.open-icon) { + .tb-rec-side { + grid-column: 2 / -1; + grid-row: 2; + margin: 10px 0 0; + justify-self: stretch; + } + + .tb-open-btn { + width: 100%; + justify-content: center; + } + } + + &:is(:not(.primary), .open-icon) { + .tb-rec-row { + grid-template-columns: auto minmax(0, 1fr) auto; + } + + .tb-rec-side { + display: contents; + } + + :is(.tb-open, .tb-open-btn) { + grid-column: 3; + grid-row: 1; + } + + .tb-open { + margin: -4px -4px 0 4px; + } + + .tb-ai-state { + grid-column: 2 / -1; + grid-row: 2; + justify-self: start; + margin-top: 6px; + } + } + + &.open-icon .tb-open-btn { + margin-left: 8px; + } + } + + .tb-list-body > .tb-rec.line { + padding: 3px 0; + min-height: 30px; + } + + .tb-rec.line { + width: auto; + display: grid; + grid-template-columns: 24px minmax(0, 1fr) auto; + column-gap: 8px; + align-items: center; + + .tb-rec-tile { + grid-row: 1; + align-self: center; + } + + .tb-rec-name { + grid-column: 2; + grid-row: 1; + } + + .tb-rec-meta { + grid-column: 2 / -1; + grid-row: 2; + min-width: 0; + } + + > .tb-ai-state { + grid-column: 3; + grid-row: 1; + } + } + + .tb-rec.line:not(:is(.tb-list-body, .tb-rec-det, .tb-disc, .k-review, .k-hand, .k-detail-recs) .tb-rec) { + grid-template-columns: 20px minmax(0, 1fr) auto; + row-gap: 0; + align-items: start; + padding: 6px 10px 6px 8px; + + .tb-rec-tile { + align-self: start; + width: 20px; + height: 20px; + background: none; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + } + } +} + +tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) ~ .k-detail-more { + margin-left: 24px; +} + +tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { + max-height: 320px; + overflow: auto; +} + +.tb-ai-mark-button { + position: relative; + isolation: isolate; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + padding: 0; + border: 0; + border-radius: 12px; + background: none; + cursor: pointer; + outline: none; + -webkit-tap-highlight-color: transparent; + transition: background-color .16s ease, transform .16s cubic-bezier(.2, .8, .2, 1); + + &:active { + transform: scale(.96); + } + + > .tb-ai-mark { + position: relative; + isolation: isolate; + pointer-events: none; + animation-play-state: paused; + transition: box-shadow .25s ease, transform .25s cubic-bezier(.2, .8, .2, 1); + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background: var(--tb-surface); + opacity: .62; + transition: opacity .25s ease; + } + } + + &:hover, &:focus-visible, &[aria-pressed="true"], &.working, &.glow { + > .tb-ai-mark { + animation-play-state: running; + + &::before { + opacity: 0; + } + } + } + + &:hover > .tb-ai-mark { + transform: scale(1.05); + box-shadow: var(--ai-mark-edge), 0 3px 12px color-mix(in oklab, var(--ai-light-teal) 60%, transparent); + } + + &[aria-pressed="true"] { + background: rgba(0, 0, 0, 0.08); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + &.glow::after { + content: ''; + position: absolute; + inset: -4px; + z-index: -1; + border-radius: 16px; + background: var(--ai-glow); + filter: blur(7px); + opacity: .7; + pointer-events: none; + animation: tb-ai-intro-breathe 1.8s ease-in-out 3 both; + } + + .tb-ai-mark-cue { + position: absolute; + top: 2px; + right: 2px; + display: flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + pointer-events: none; + + &::before { + content: ''; + display: block; + width: 10px; + height: 10px; + border-radius: 50%; + box-shadow: 0 0 0 2px var(--tb-ai-cue-ring, var(--tb-primary-background-color, #fff)); + } + + &.needs::before { + background: var(--tb-caution); + } + + &.error::before { + width: 8px; + height: 8px; + border-radius: 1.5px; + background: var(--tb-crit); + transform: rotate(45deg); + } + } + + @media (prefers-reduced-motion: reduce) { + &, > .tb-ai-mark, > .tb-ai-mark::before { + transition: none; + } + + &:active, &:hover > .tb-ai-mark { + transform: none; + } + + &.glow::after { + animation: none; + } + } +} + +.tb-primary-panels .mat-toolbar .tb-ai-mark-button { + --tb-ai-cue-ring: var(--tb-primary-contrast-500, #fff); + + &[aria-pressed="true"] { + background: color-mix(in srgb, var(--tb-primary-contrast-500, #fff) 18%, transparent); + } + + &:focus-visible { + outline-color: var(--tb-primary-contrast-500, #fff); + } +} + +@keyframes tb-ai-intro-breathe { + 0%, 100% { opacity: .7; } + 50% { opacity: .25; } +} + +.k-hand { + position: relative; + padding: calc(var(--chat-card-pad) - 2px) var(--chat-card-pad); + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 6px 18px rgba(16, 24, 40, 0.06); + font-family: var(--tb-font); + font-size: 14px; + line-height: 20px; + letter-spacing: .25px; + color: var(--tb-ink); + + > .k-head { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + column-gap: 6px; + row-gap: 2px; + align-items: center; + padding-right: 44px; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + font-weight: 500; + white-space: nowrap; + color: var(--tb-caution-text); + + > .mat-icon { + margin-top: 1px; + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + } + + .k-sub { + grid-column: 1 / -1; + min-width: 0; + white-space: normal; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + + &::first-letter { + text-transform: uppercase; + } + } + } + + > .k-time { + position: absolute; + right: 16px; + top: 14px; + } + + > .k-hand-close { + position: absolute; + right: 6px; + top: 4px; + color: var(--tb-ink-54); + } + + > .k-body { + margin-top: 10px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + text-wrap: pretty; + + > * + * { + margin-top: 12px; + } + + p { + margin: 0; + font-size: inherit; + line-height: inherit; + letter-spacing: inherit; + } + + .tb-markdown-view [class*="tb-markdown-view-"] { + > p, > div, > ul, > ol, > table, > h1, > h2, > h3, > h4, > h5, > h6 { + padding-left: 0; + padding-right: 0; + margin-left: 0; + } + + p, li { + padding: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: .25px; + color: var(--tb-ink); + } + + > * + * { + margin-top: 8px; + } + + ul, ol { + margin-bottom: 0; + padding-left: 22px; + } + + li + li { + margin-top: 4px; + } + + h1, h2, h3, h4, h5, h6 { + padding: 0; + margin-bottom: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + } + + strong, b { + font-weight: 500; + } + + code:not([class*=language-]):not(pre code) { + display: inline-block; + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + letter-spacing: 0; + color: var(--tb-ink); + vertical-align: baseline; + } + } + + > .k-wait:last-child, > .k-quiet:last-child, > .k-waitrow:last-child { + margin: 14px calc(-1 * var(--chat-card-pad)) 0; + padding: 12px var(--chat-card-pad) 0; + border-top: 1px solid var(--k-stroke); + } + } + + &.done { + padding: 10px 16px; + background: transparent; + box-shadow: none; + + > .k-head { + color: var(--tb-text-secondary); + + .k-sub { + font-size: 14px; + line-height: 20px; + color: var(--tb-ink-76); + } + } + + > .k-body { + margin-top: 4px; + color: var(--tb-text-secondary); + } + } + + .k-steps { + list-style: none; + margin-inline: 0; + margin-bottom: 0; + padding: 0; + + &:first-child { + margin-top: 0; + } + + display: grid; + gap: 10px; + + > li { + min-width: 0; + } + + li label { + display: grid; + grid-template-columns: 16px minmax(0, 1fr); + column-gap: 12px; + row-gap: 1px; + align-items: start; + cursor: pointer; + } + + input { + width: 16px; + height: 16px; + margin: 2px 0 0; + accent-color: var(--ai-deep); + } + + .k-step-t { + font-weight: 500; + color: var(--tb-ink); + } + + .k-step-d { + grid-column: 2; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-76); + } + + li.done .k-step-t { + font-weight: 400; + color: var(--tb-text-secondary); + text-decoration: line-through; + text-decoration-color: var(--tb-ink-38); + } + + .k-step-file { + display: flex; + width: auto; + max-width: calc(100% - 28px); + margin: 8px 0 2px 28px; + } + + .k-step-x { + margin: 8px 0 2px 28px; + min-width: 0; + + > * + * { + margin-top: 6px; + } + } + } + + .k-value { + min-width: 0; + + .k-value-ic { + flex: none; + color: rgba(255, 255, 255, 0.42); + } + } + + .k-choice-panel { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 10px; + } + + .k-choice { + display: grid; + grid-template-columns: 24px auto minmax(0, 1fr); + align-items: center; + gap: 10px; + + .k-qi { + display: inline-flex; + color: var(--tb-ink-54); + } + + .k-qt { + color: var(--tb-ink); + } + } + + .k-seg { + display: inline-flex; + flex-wrap: wrap; + justify-self: start; + border: 1px solid var(--k-stroke); + border-radius: 8px; + overflow: hidden; + + button { + display: inline-flex; + align-items: center; + gap: 6px; + height: 32px; + padding: 0 12px; + border: 0; + border-left: 1px solid var(--k-stroke); + background: var(--tb-surface); + font: 500 13px/20px var(--tb-font); + color: var(--tb-ink); + cursor: pointer; + + &:first-child { + border-left: 0; + } + + .mat-icon { + color: var(--tb-ink-54); + } + + &[aria-pressed="true"] { + background: var(--ai-deep); + color: #fff; + + .mat-icon { + color: inherit; + } + } + } + } + + .k-choice-body { + padding-left: 34px; + color: var(--tb-ink-76); + } + + .k-wait { + display: flex; + align-items: flex-start; + gap: 8px; + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); + + tb-ai-spin { + --spin: 20px; + flex: none; + } + + .clock { + color: var(--k-faint); + font-variant-numeric: tabular-nums; + } + + .k-wait-tools { + display: inline-flex; + gap: 2px; + margin: -2px 0 -2px auto; + } + + .k-wait-tool { + 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-38); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus, var(--ai-deep)); + outline-offset: 1px; + } + } + + &:hover .k-wait-tool { + color: var(--tb-ink-76); + } + + &.warn { + align-items: center; + color: var(--tb-caution-text); + + > span:not(.clock):not(.mat-icon) { + font-family: var(--tb-font); + font-weight: 500; + } + + .mat-icon { + color: var(--tb-caution); + } + } + } + + .k-waitrow { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 8px; + + .k-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + + .ob-chip { + height: 28px; + padding: 0 10px; + font-size: var(--chat-line); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + } + } + + .k-test-note { + margin: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-76); + + &.warn { + color: var(--tb-caution-text); + } + } + + .k-test { + display: block; + + .ob-hint { + margin: 0 0 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .k-test-slot { + margin-bottom: 8px; + } + } + + .k-outcomes { + border-collapse: collapse; + width: 100%; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + + td { + padding: 6px 10px 6px 0; + border-top: 1px solid var(--tb-line-soft); + vertical-align: top; + color: var(--tb-ink-76); + } + + tr:first-child td { + border-top: 0; + } + + td:first-child { + width: 45%; + } + + code { + display: inline-block; + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + overflow-wrap: anywhere; + } + + tr.ok code { + color: var(--tb-ok-text); + } + + tr.warn code { + color: var(--tb-caution-text); + } + } + + .k-quiet { + display: grid; + gap: 8px; + + .ob-hint { + margin: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .k-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 2px; + } + + .ob-chip { + height: 28px; + padding: 0 10px; + font-size: var(--chat-line); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + } + } +} + +@media (max-width: 599px) { + .k-hand { + > .k-head { + flex-wrap: wrap; + + .k-sub { + flex-basis: 100%; + margin-left: 26px; + } + } + + .k-choice { + grid-template-columns: 24px minmax(0, 1fr); + + .k-seg { + grid-column: 2; + } + } + } +} + +img.tb-ai-fade-in { + opacity: 0; + transition: opacity .25s ease; + + &.loaded { + opacity: 1; + } +} + +.k-fact-chip { + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + box-sizing: border-box; + padding: 0 8px 0 6px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--tb-line); + line-height: 22px; + white-space: nowrap; + + img { + width: 16px; + height: 16px; + object-fit: contain; + } + + .mat-icon { + color: var(--tb-ink-54); + } +} diff --git a/ui-ngx/src/theme/app-theme.scss b/ui-ngx/src/theme/app-theme.scss index 682d7c1cf9..5da9183aeb 100644 --- a/ui-ngx/src/theme/app-theme.scss +++ b/ui-ngx/src/theme/app-theme.scss @@ -2,31 +2,13 @@ // SPDX-License-Identifier: BUSL-1.1 @use '@angular/material' as mat; @use './app-theme-overwrites' as overwrites; -@use '@angular/material/core/tokens/m2-utils'; @import './datepicker-theme'; -@import './theme-constants'; +@import './app-theme-palette'; +@import './ai-theme'; @include mat.elevation-classes(); @include mat.app-background(); -$tb-primary: mat.m2-define-palette($mat-tb-primary); -$tb-accent: mat.m2-define-palette($mat-tb-accent); - -$tb-mat-theme: mat.m2-define-light-theme(( - color: ( - primary: $tb-primary, - accent: $tb-accent - ), - typography: mat.m2-define-typography-config( - $button: mat.m2-define-typography-level(14px, 36px, 500, $letter-spacing: 0.03125em) - ), - density: 0 -)); - -$tb-theme-system: m2-utils.get-system($tb-mat-theme); -$tb-theme-system: map_merge($tb-theme-system, ( background: map_get(mat.$m2-grey-palette, 200) )); -$tb-theme: map_merge($tb-mat-theme, (_mat-system: $tb-theme-system)); - .tb-default { @include mat.all-component-themes($tb-theme); @include mat-datetimepicker-theme($tb-theme); diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 8ced11ade3..5f1342f270 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -840,6 +840,16 @@ dependencies: tslib "^2.3.0" +"@fontsource-variable/roboto-mono@^5.3.0": + version "5.3.0" + resolved "https://registry.yarnpkg.com/@fontsource-variable/roboto-mono/-/roboto-mono-5.3.0.tgz#10c0f1c0c283a61fa1e0f24381a1e62ed6ad45fa" + integrity sha512-h5r+KY/6qy8JEOj33JgcrFO81YAnvrc1EAwMpl/EPJLb2OIvOy0/jmB5M7qs7x/uXk5JUP5Ux4LrkeOK7faHkQ== + +"@fontsource-variable/roboto@^5.3.0": + version "5.3.0" + resolved "https://registry.yarnpkg.com/@fontsource-variable/roboto/-/roboto-5.3.0.tgz#3ddf845c018b0ea9d15b36e06515d0ebdb02f49e" + integrity sha512-BoaaZiQf8fgtxv07KXkTwx1bKz/EoqIlTXq2OOKKXINxp6qXWdnlChqV+hSaDANS49yyUASFl3OVBMMDTCIHFA== + "@fullcalendar/angular@^6.1.20": version "6.1.22" resolved "https://registry.yarnpkg.com/@fullcalendar/angular/-/angular-6.1.22.tgz#0820b2cd38154418b30278acd359f7be91206fc2" @@ -8407,16 +8417,6 @@ typed-array-length@^1.0.7: possible-typed-array-names "^1.0.0" reflect.getprototypeof "^1.0.6" -typeface-roboto-mono@^1.1.13: - version "1.1.13" - resolved "https://registry.yarnpkg.com/typeface-roboto-mono/-/typeface-roboto-mono-1.1.13.tgz#2af8662db8f9119c00efd55d6ed8877d2a69ec94" - integrity sha512-pnzDc70b7ywJHin/BUFL7HZX8DyOTBLT2qxlJ92eH1UJOFcENIBXa9IZrxsJX/gEKjbEDKhW5vz/TKRBNk/ufQ== - -typeface-roboto@^1.1.13: - version "1.1.13" - resolved "https://registry.yarnpkg.com/typeface-roboto/-/typeface-roboto-1.1.13.tgz#9c4517cb91e311706c74823e857b4bac9a764ae5" - integrity sha512-YXvbd3a1QTREoD+FJoEkl0VQNJoEjewR2H11IjVv4bp6ahuIcw0yyw/3udC4vJkHw3T3cUh85FTg8eWef3pSaw== - typescript-eslint@^8.72.0: version "8.72.0" resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-8.72.0.tgz#50a8fd6d4304ffd1e7fd375f8a439c6f15488071"