Browse Source

Merge pull request #16848 from thingsboard/feature/ai-chat

AI Assistant page, chat kit, docked AI chat on every page, solution creator in chat, new Home, AI credits and limit requests
pull/16850/head
Viacheslav Klimov 5 days ago
committed by GitHub
parent
commit
8b2b01a756
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 17
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  2. 24
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  3. 56
      application/src/main/java/org/thingsboard/server/controller/NotificationController.java
  4. 20
      application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java
  5. 28
      application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java
  6. 6
      application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
  7. 3
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  8. 4
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  9. 14
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  10. 6
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  11. 21
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  12. 2
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  13. 5
      application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java
  14. 41
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java
  15. 8
      application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java
  16. 4
      application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java
  17. 45
      application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java
  18. 33
      application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java
  19. 34
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  20. 22
      application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
  21. 2
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
  22. 4
      application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java
  23. 56
      application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java
  24. 137
      application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java
  25. 69
      application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java
  26. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java
  27. 1
      common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java
  28. 40
      common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java
  29. 2
      common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java
  30. 2
      dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java
  31. 7
      dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java
  32. 4
      dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotificationSettingsService.java
  33. 35
      dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java
  34. 5
      dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java
  35. 5
      dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java
  36. 2
      dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java
  37. 60
      dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java
  38. 71
      dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java
  39. 2
      pom.xml
  40. 18
      tools/src/main/python/license-headers/curations.json
  41. 4
      ui-ngx/package.json
  42. 18
      ui-ngx/src/app/core/auth/auth.actions.ts
  43. 21
      ui-ngx/src/app/core/auth/auth.effects.ts
  44. 14
      ui-ngx/src/app/core/auth/auth.reducer.ts
  45. 25
      ui-ngx/src/app/core/auth/auth.selectors.ts
  46. 5
      ui-ngx/src/app/core/http/admin.service.ts
  47. 14
      ui-ngx/src/app/core/http/ai-chat.service.ts
  48. 4
      ui-ngx/src/app/core/http/custom-menu.service.ts
  49. 4
      ui-ngx/src/app/core/http/notification.service.ts
  50. 16
      ui-ngx/src/app/core/http/solutions-creator.service.ts
  51. 8
      ui-ngx/src/app/core/http/user-permissions.service.ts
  52. 21
      ui-ngx/src/app/core/local-storage/stored.ts
  53. 5
      ui-ngx/src/app/core/notification/notification.models.ts
  54. 36
      ui-ngx/src/app/core/services/ai-assistant-config.service.ts
  55. 355
      ui-ngx/src/app/core/services/ai-assistant-panel.service.ts
  56. 353
      ui-ngx/src/app/core/services/ai-chats.service.ts
  57. 73
      ui-ngx/src/app/core/services/ai-slash.service.ts
  58. 253
      ui-ngx/src/app/core/services/ai-solutions.service.ts
  59. 37
      ui-ngx/src/app/core/services/menu.models.ts
  60. 71
      ui-ngx/src/app/core/services/tour.service.ts
  61. 506
      ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss
  62. 40
      ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss
  63. 187
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html
  64. 271
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts
  65. 2263
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts
  66. 43
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html
  67. 95
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss
  68. 185
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts
  69. 817
      ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts
  70. 155
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html
  71. 78
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss
  72. 445
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts
  73. 23
      ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html
  74. 134
      ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts
  75. 253
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts
  76. 58
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts
  77. 126
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html
  78. 247
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss
  79. 674
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  80. 23
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html
  81. 5
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss
  82. 26
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts
  83. 19
      ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts
  84. 31
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html
  85. 154
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss
  86. 13
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts
  87. 52
      ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts
  88. 280
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  89. 620
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  90. 993
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  91. 56
      ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts
  92. 49
      ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html
  93. 144
      ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss
  94. 67
      ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts
  95. 480
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html
  96. 792
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss
  97. 1524
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  98. 938
      ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts
  99. 33
      ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts
  100. 44
      ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts

17
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 {

24
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,

56
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<String, Long> 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 " +

20
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;
}
}

28
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;
}
}

6
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());

3
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);
}
}

4
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);

14
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(

6
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);
}

21
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);
}
}

2
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<String> CLIENT_CAPABILITIES = List.of();
static final List<String> CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY);
private final TbAiChannelPool.PoolKey key;
private final String origin;

5
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<HasTitle> EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle());
private final UserSettingsService settingsService;

41
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");
}
}

8
application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java

@ -422,7 +422,13 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc
List<EntityData> 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 {

4
application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java

@ -66,6 +66,9 @@ public abstract class TbAbstractDataSubCtx<T extends AbstractDataQuery<? extends
return query != null && query.getPageLink().isDynamic();
}
protected void onSameEntities(Map<EntityId, EntityData> newDataMap) {
}
@Override
protected synchronized void update() {
PageData<EntityData> newData = findEntityData();
@ -78,6 +81,7 @@ public abstract class TbAbstractDataSubCtx<T extends AbstractDataQuery<? extends
Map<EntityId, EntityData> 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);

45
application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java

@ -101,7 +101,10 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
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<AlarmData> alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(),
getMergedUserPermissions(), query, getOrderedEntityIds());
@ -116,9 +119,39 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
sendWsMsg(update);
}
public boolean isOwnerScoped() {
return query != null && query.getEntityFilter() == null;
}
private PageData<AlarmData> findOwnerAlarms() {
long start = System.currentTimeMillis();
PageData<AlarmData> 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<AlarmData> 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<AlarmDataQuery> {
}
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<AlarmDataQuery> {
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<AlarmDataQuery> {
}
public synchronized void checkAndResetInvocationCounter() {
if (isOwnerScoped()) {
resetInvocationCounter();
refreshOwnerAlarms();
return;
}
boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval;
resetInvocationCounter();
if (fetchNeeded) {

33
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<EntityDataQuery> {
});
}
@Override
protected void onSameEntities(Map<EntityId, EntityData> newDataMap) {
List<EntityData> changed = new ArrayList<>();
for (EntityData current : data.getData()) {
EntityData fresh = newDataMap.get(current.getEntityId());
Map<String, TsValue> 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<String, TsValue> current, Map<String, TsValue> fresh) {
if (current == null || current.size() != fresh.size()) {
return false;
}
for (Map.Entry<String, TsValue> 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<EntityId, EntityData> newDataMap) {
this.updateLatestTsData(this.data);

34
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<TbAiClient.TbAiResponse> captureProcessCall() {
private TbAiService.TbAiCall<TbAiClient.TbAiResponse> captureProcessCall(boolean checkCredits) {
ArgumentCaptor<TbAiService.TbAiCall> 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();
}

22
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

2
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);

4
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<String> SQL_LESS_ALLOWED = Set.of("4.3.1.5");
private static final Set<String> SQL_LESS_ALLOWED = Set.of("4.3.1.5", "4.4.2.0");
@Autowired
private MigrationService migrationService;

56
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());
}
}

137
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<AlarmData> 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<AlarmData> fresh = new PageData<>(List.of(alarmData(), alarmData()), 1, 2, false);
given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))).willReturn(fresh);
subCtx.checkAndResetInvocationCounter();
ArgumentCaptor<CmdUpdate> 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);
}
}

69
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<Integer, EntityId> 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<String, TsValue> 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<CmdUpdate> 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<String, TsValue> currentFields(EntityId entityId) {
PageData<EntityData> data = (PageData<EntityData>) 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<EntityKeyType, Map<String, TsValue>> 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);
}
}

2
common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java

@ -109,6 +109,8 @@ public interface AlarmService extends EntityDaoService {
PageData<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions,
AlarmDataQuery query, Collection<EntityId> orderedEntityIds);
PageData<AlarmData> findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query);
Set<EntityId> getPropagationEntityIds(Alarm alarm);
Set<EntityId> getPropagationEntityIds(Alarm alarm, List<EntityType> types);

1
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,

40
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<String, String> getTemplateData() {
return mapOf(
"userEmail", userEmail,
"tenantName", tenantName,
"limitDescription", limitDescription,
"increaseLimitActionLabel", increaseLimitActionLabel,
"increaseLimitLink", increaseLimitLink,
"baseUrl", baseUrl
);
}
}

2
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),

2
dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java

@ -73,6 +73,8 @@ public interface AlarmDao extends Dao<Alarm> {
PageData<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions,
AlarmDataQuery query, Collection<EntityId> orderedEntityIds);
PageData<AlarmData> findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query);
Set<AlarmSeverity> findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId);
/**

7
dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java

@ -217,6 +217,13 @@ public class BaseAlarmService extends AbstractCachedEntityService<TenantId, Page
return alarmDao.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, query, orderedEntityIds);
}
@Override
public PageData<AlarmData> 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) {

4
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()

35
dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java

@ -230,6 +230,41 @@ public class DefaultNotifications {
</table>""")
.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("""
<table style="box-sizing: border-box; border-radius: 3px; width: 100%; background-color: #f6f6f6; margin: 0px auto;" cellspacing="0" cellpadding="0" bgcolor="#f6f6f6">
<tbody>
<tr style="box-sizing: border-box; margin: 0px;">
<td style="box-sizing: border-box; vertical-align: middle; margin: 0px; padding: 40px;" align="center" valign="middle">
<table style="box-sizing: border-box; border: 1px solid #E0E0E0; border-radius: 3px; margin: 0px; background-color: #ffffff; max-width: 600px !important;" cellspacing="0" cellpadding="0">
<tbody>
<tr style="box-sizing: border-box; margin: 0px;">
<td style="box-sizing: border-box; vertical-align: middle; border-bottom: 1px solid #E0E0E0; margin: 0px; padding: 20px; color: #212121; font-family: Arial; font-size: 20px; line-height: 20px; font-style: normal; font-weight: bold;" valign="middle">AI credits limit increase request</td>
</tr>
<tr style="box-sizing: border-box; margin: 0px;">
<td style="box-sizing: border-box; vertical-align: top; margin: 0px; padding: 16px 24px; color: #212121; font-family: Arial; font-size: 16px; line-height: 24px; font-weight: 400;" valign="top">${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits.</td>
</tr>
<tr style="box-sizing: border-box; margin: 0px;">
<td style="box-sizing: border-box; vertical-align: top; margin: 0px; padding: 0 24px 16px 24px; color: #212121; font-family: Arial; font-size: 16px; line-height: 24px; font-weight: 400;" valign="top">
<a style="display: inline-block; padding: 10px 16px; border-radius: 4px; background: #106CC8; color: #fff; font-family: Arial; font-size: 14px; line-height: 20px; font-weight: bold; text-decoration: none;" href="${baseUrl}${increaseLimitLink}">${increaseLimitActionLabel}</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>""")
.build())
.build();
public static final DefaultNotification apiFeatureWarningForSysadmin = DefaultNotification.builder()
.name("API feature warning notification for sysadmin")
.type(NotificationType.API_USAGE_LIMIT)

5
dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java

@ -309,6 +309,11 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
return alarmQueryRepository.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, query, orderedEntityIds);
}
@Override
public PageData<AlarmData> findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) {
return alarmQueryRepository.findAlarmDataByQuery(tenantId, customerId, mergedUserPermissions, query);
}
@Override
public Set<AlarmSeverity> findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId) {
return alarmRepository.findAlarmSeverities(tenantId.getId(), entityId.getId(), entityId.getEntityType().name(),

5
dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java

@ -36,7 +36,8 @@ public class AlarmDataAdapter {
public static PageData<AlarmData> createAlarmData(EntityDataPageLink pageLink,
List<Map<String, Object>> rows,
int totalElements, Collection<EntityId> orderedEntityIds) {
Map<UUID, EntityId> entityIdMap = orderedEntityIds.stream().collect(Collectors.toMap(EntityId::getId, Function.identity()));
Map<UUID, EntityId> 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);

2
dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java

@ -19,6 +19,8 @@ public interface AlarmQueryRepository {
PageData<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions,
AlarmDataQuery query, Collection<EntityId> orderedEntityIds);
PageData<AlarmData> findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query);
long countAlarmsByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmCountQuery query, Collection<EntityId> orderedEntityIds);
}

60
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<String, String> alarmFieldColumnMap = new HashMap<>();
private static final Set<String> 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<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions,
AlarmDataQuery query, Collection<EntityId> orderedEntityIds) {
return findAlarmData(tenantId, null, mergedUserPermissions, query, orderedEntityIds);
}
@Override
public PageData<AlarmData> findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) {
return findAlarmData(tenantId, customerId, mergedUserPermissions, query, null);
}
private PageData<AlarmData> findAlarmData(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions,
AlarmDataQuery query, Collection<EntityId> 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<Map<String, Object>> rows;

71
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<AlarmData> 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<AlarmData> 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<AlarmData> 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<AlarmData> 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());
}

2
pom.xml

@ -81,7 +81,7 @@
<pkg.unixLogFolder>/var/log/${pkg.name}</pkg.unixLogFolder>
<pkg.installFolder>/usr/share/${pkg.name}</pkg.installFolder>
<pkg.controlScriptsFolder>control</pkg.controlScriptsFolder>
<thingsboard.ai.version>2.1.10</thingsboard.ai.version>
<thingsboard.ai.version>2.1.11-SNAPSHOT</thingsboard.ai.version>
<thingsboard.client.version>4.4.0</thingsboard.client.version>
<spring-boot.version>4.1.3</spring-boot.version>
<netty.version>4.2.20.Final</netty.version> <!-- must match spring-boot-dependencies -->

18
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",

4
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"
},

18
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;

21
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,

14
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 }};

25
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<AppState>): AuthState => {
let state: AuthState;

5
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<FeaturesInfo>('/api/admin/featuresInfo', defaultHttpOptionsFromConfig(config));
}
public getLicenseUsageInfo(config?: RequestConfig): Observable<LicenseUsageInfo> {
return this.http.get<LicenseUsageInfo>('/api/admin/licenseUsageInfo', defaultHttpOptionsFromConfig(config));
}
public getSubscriptionInfo(config?: RequestConfig): Observable<SubscriptionInfo> {
return this.http.get<SubscriptionInfo>('/api/admin/subscriptionInfo', defaultHttpOptionsFromConfig(config));
}

14
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<Array<ChatInfo>>(`/api/ai/chats`, defaultHttpOptionsFromConfig(config))
}
public listChatStatuses(config?: RequestConfig): Observable<Array<ChatInfo>> {
return this.http.get<Array<ChatInfo>>(`/api/ai/chats/status`, defaultHttpOptionsFromConfig(config));
}
public createChat(chat: ChatConfiguration, config?: RequestConfig): Observable<string> {
return this.http.post<string>(`/api/ai/chats`, chat, defaultHttpOptionsFromConfig(config));
}
public updatedChat(chatId: string, chat: ChatConfiguration, config?: RequestConfig): Observable<void> {
public updatedChat(chatId: string, chat: ChatUpdate, config?: RequestConfig): Observable<void> {
return this.http.patch<void>(`/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<void> {
return this.http.post<void>(`/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<ChatEvent> = {};
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();

4
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<CustomMenuConfig> {
return this.http.get<CustomMenuConfig>('/api/customMenu')
.pipe(
map(customMenuConfig => withCurrentMenuIds(customMenuConfig)),
tap((customMenuConfig) => {
this.customMenuConfig = customMenuConfig;
if (notify) {

4
ui-ngx/src/app/core/http/notification.service.ts

@ -66,6 +66,10 @@ export class NotificationService {
return this.http.post<void>(`/api/notification/sendAddonAccessRequest/${addonType}`, null, defaultHttpOptionsFromConfig(config));
}
public sendAiCreditsLimitIncreaseRequest(limitType: 'TENANT' | 'POOL', config?: RequestConfig): Observable<void> {
return this.http.post<void>(`/api/notification/aiCreditsLimitIncreaseRequest?limitType=${limitType}`, null, defaultHttpOptionsFromConfig(config));
}
public sendPlanUpgradeRequest(planName: string, config?: RequestConfig): Observable<void> {
return this.http.post<void>(`/api/notification/sendPlanUpgradeRequest/${planName}`, null, defaultHttpOptionsFromConfig(config));
}

16
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<void>(`/api/ai/solution/${solutionId}/${step}/clear`, defaultHttpOptionsFromConfig(config));
}
public stopSolution(solutionId: string, config?: RequestConfig): Observable<boolean> {
return this.http.post<boolean>(`/api/ai/solution/${solutionId}/stop`, null, defaultHttpOptionsFromConfig(config));
}
public createSolution(solutionId: string, config?: RequestConfig): Observable<SolutionCreatorInfo> {
return this.http.post<SolutionCreatorInfo>(`/api/ai/solution/${solutionId}/create`, '', defaultHttpOptionsFromConfig(config));
}
@ -64,4 +70,12 @@ export class SolutionsCreatorService {
public deleteSolution(solutionId: string, config?: RequestConfig): Observable<void> {
return this.http.delete<void>(`/api/ai/solution/${solutionId}`, defaultHttpOptionsFromConfig(config));
}
public updateSolution(solutionId: string, request: SolutionUpdateRequest, config?: RequestConfig): Observable<void> {
return this.http.post<void>(`/api/ai/solution/${solutionId}/update`, request, defaultHttpOptionsFromConfig(config));
}
public getInstallProgress(solutionId: string, config?: RequestConfig): Observable<SolutionInstallProgress> {
return this.http.get<SolutionInstallProgress>(`/api/ai/solution/${solutionId}/progress`, defaultHttpOptionsFromConfig(config));
}
}

8
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;

21
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;
}
}

5
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 {

36
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')
};
}
}

355
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<string, AiChatClientContext>();
private _chats = signal<ChatInfo[] | null>(null);
readonly chats = this._chats.asReadonly();
private _lastChatIdByContext = new Map<string, string>();
private _lastChatIdByContext = AiAssistantPanelService.readChats();
private static readonly AUTO_APPROVE_STORAGE_KEY = 'aiAssistantAutoApproveChats';
private localStorage = inject(LocalStorageService);
private store = inject(Store<AppState>);
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<string, string> {
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<Set<string>>(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<Array<EntityId>>();
readonly updatedData$ = this._updatedData$.asObservable();
readonly updatedDataBatches$: Observable<Array<EntityId>> = 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<string> {
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<string | null>(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<T>(view: AiChatView, name: string | null | undefined, until: Observable<T>): Observable<T> {
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<AiCustomizationSaved>();
readonly customizationSaved$ = this._customizationSaved$.asObservable();
customizationReload$(kind: AiCustomizationSaved['kind'], clean: () => boolean = () => true): Observable<AiCustomizationSaved> {
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<EntityId>): 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);
});
}
}

353
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<ChatInfo[]>([]);
readonly chats = this._chats.asReadonly();
private _loaded = signal(false);
readonly loaded = this._loaded.asReadonly();
private _replying = signal<ReadonlySet<string>>(new Set());
readonly replying = this._replying.asReadonly();
private _waiting = signal<ReadonlySet<string>>(new Set());
private _open = signal<ReadonlySet<string>>(new Set());
private _failed = signal<ReadonlyMap<string, string>>(new Map());
private static readonly STATUS_POLL_MS = 15000;
private _statuses = signal<ChatInfo[]>([]);
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<AppState>);
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<ChatInfo[]> {
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<ChatInfo[]> {
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<ChatInfo> {
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<void> {
return this.aiChat.updatedChat(chatId, {title}, {ignoreLoading: true, ignoreErrors: true}).pipe(
tap(() => this.setTitle(chatId, title))
);
}
sendFeedback(chatId: string, feedback: AnswerFeedback): Observable<void> {
return this.aiChat.updatedChat(chatId, {feedback}, {ignoreLoading: true});
}
isAutoApprove(chatId: string | undefined): boolean {
return !!this.find(chatId)?.autoApprove;
}
setAutoApprove(chatId: string, autoApprove: boolean): Observable<void> {
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<void> {
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<void> {
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<boolean> {
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<ReadonlySet<string>>, 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;
});
}
}

73
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<AiSlashComposer>();
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());
}
}
}

253
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<SolutionInfo[]>([]);
readonly solutions = this._solutions.asReadonly();
private _loaded = signal(false);
readonly loaded = this._loaded.asReadonly();
private _running = signal<ReadonlySet<string>>(new Set());
readonly running = this._running.asReadonly();
private _failed = signal<ReadonlyMap<string, string>>(new Map());
private api = inject(SolutionsCreatorService);
private dialog = inject(DialogService);
private translate = inject(TranslateService);
private generation = 0;
private userWatch = inject(Store<AppState>).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<SolutionInfo[]> {
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<SolutionInfo>): void {
this._solutions.update(list => list.map(item => item.id === solutionId ? {...item, ...fields} : item));
}
rename(solution: SolutionInfo, title: string): Observable<SolutionCreatorInfo> {
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<void> {
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<void> {
return this.api.updateSolution(solutionId, {step, feedback}, {ignoreLoading: true});
}
installProgress(solutionId: string): Observable<SolutionInstallProgress> {
return this.api.getInstallProgress(solutionId, {ignoreLoading: true, ignoreErrors: true});
}
confirmAndUninstall(solution: SolutionInfo): Observable<SolutionCreatorInfo | null> {
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<void> {
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<boolean> {
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))
);
}
}

37
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<MenuId, MenuSection>([
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<MenuId, MenuSection>([
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, MenuFilter>([
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, MenuReference[]>([
Authority.TENANT_ADMIN,
[
{id: MenuId.home},
{id: MenuId.ai_assistant},
{id: MenuId.iot_hub},
{id: MenuId.ai_solution_creator},
{
id: MenuId.monitor,
pages: [

71
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<void>;
}
const OFFER_DELAY_MS = 1200;
@Injectable({providedIn: 'root'})
export class TourService {
readonly active = signal(false);
private store = inject(Store<AppState>);
private injector = inject(Injector);
private userPermissions = inject(UserPermissionsService);
private chats = inject(AiChatsService);
private dialog = inject(MatDialog);
private launcher: Promise<TourLauncherApi> | 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<TourLauncherApi> {
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;
}
}

506
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);
}
}

40
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;
}
}

187
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html

@ -0,0 +1,187 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
@if (hood()) {
<p class="k-hood"><mat-icon class="tb-mat-16" aria-hidden="true">code</mat-icon><span>{{ hood() }}</span></p>
}
@for (block of view().blocks; track $index) {
@switch (block.type) {
@case ('hub') {
<div class="k-detail-recs k-detail-hub tb-list-body" role="list">
@for (rec of shown(hub(), 'hub'); track rec.key) {
<tb-ai-record role="listitem" [entityType]="rec.entityType" [alarmRule]="rec.alarmRule" [name]="rec.name" [badge]="rec.badge" [url]="rec.url"
[hub]="rec.hub"></tb-ai-record>
}
@if (hub().length > LIST_SHOWN) {
<ng-container *ngTemplateOutlet="moreToggle; context: {key: 'hub', count: hub().length - LIST_SHOWN}"></ng-container>
}
</div>
}
@case ('records') {
@if (block.label) {
<div class="k-detail-label">{{ say(block.label) }}</div>
}
<div class="k-detail-recs k-detail-list tb-list-body" role="list">
@for (row of shown(block.rows, 'records' + $index); track $index) {
<div class="tb-rec line" [attr.data-pal]="kind(row.entityType).palette">
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ kind(row.entityType).icon }}</mat-icon></span>
@if (recordUrl(row); as url) {
<a class="tb-rec-name" [routerLink]="url">{{ row.name }}</a>
} @else {
<span class="tb-rec-name">{{ row.name }}</span>
}
@if (row.meta) {
<span class="tb-rec-meta">{{ row.meta }}</span>
}
</div>
}
@if (block.rows.length > LIST_SHOWN) {
<ng-container *ngTemplateOutlet="moreToggle; context: {key: 'records' + $index, count: block.rows.length - LIST_SHOWN}"></ng-container>
}
</div>
@if (more(block); as rest) {
<div class="k-detail-more">{{ 'ai-assistant.detail.more' | translate:{count: rest} }}</div>
}
}
@case ('values') {
@if (block.label) {
<div class="k-detail-label">{{ say(block.label) }}</div>
}
<div class="k-tels">
@for (row of block.rows; track $index) {
<span class="k-tel" [matTooltip]="row.time ? time(row.time) : ''" [matTooltipDisabled]="!row.time" matTooltipPosition="above"><code class="k-tel-key">{{ row.key }}</code><span class="k-tel-val">{{ row.value }}</span></span>
}
</div>
}
@case ('series') {
<div class="k-series">
@for (row of block.rows; track row.key) {
<div class="k-series-row">
<code class="k-tel-key">{{ row.key }}</code>
<svg class="k-series-spark" viewBox="0 0 96 20" preserveAspectRatio="none" aria-hidden="true"><path [attr.d]="row.path"></path></svg>
<span class="k-series-meta">{{ 'ai-assistant.detail.series' | translate:{points: row.points, min: number(row.min), max: number(row.max), last: number(row.last)} }}</span>
</div>
}
</div>
}
@case ('keys') {
@if (block.label) {
<div class="k-detail-label">{{ say(block.label) }}</div>
}
<div class="k-tels">
@for (key of block.keys; track $index) {
<code class="k-tel-key">{{ key }}</code>
}
</div>
}
@case ('facts') {
<dl class="k-fields k-detail-facts">
@for (fact of block.rows; track $index) {
<dt>{{ label(fact) }}</dt>
<dd [class.mono]="fact.mono">
@if (fact.images; as pair) {
<span class="k-detail-images">
@if (pair.current) {
<img tbAiFadeIn class="k-detail-img was" [src]="pair.current | image: {preview: true, ignoreLoadingImage: true} | async" alt="">
<mat-icon class="tb-mat-16" aria-hidden="true">arrow_forward</mat-icon>
}
@if (pair.value) {
<img tbAiFadeIn class="k-detail-img" [src]="pair.value | image: {preview: true, ignoreLoadingImage: true} | async" alt="">
} @else {
{{ 'ai-assistant.review.not-set' | translate }}
}
</span>
} @else if (fact.chip; as chip) {
<span class="k-fact-chip">
@if (chip.image) {
<img [src]="chip.image" alt="" aria-hidden="true">
} @else if (chip.icon) {
<mat-icon class="tb-mat-16" aria-hidden="true">{{ chip.icon }}</mat-icon>
}
{{ factValue(fact) }}
</span>
} @else if (factLink(fact); as url) {
<a [routerLink]="url">{{ factValue(fact) }}</a>
} @else if (fact.secret && !revealed().has(view().hood?.key + $index)) {
<span>{{ masked(factValue(fact)) }}</span>
<button type="button" class="k-reveal" (click)="reveal(view().hood?.key + $index)" [attr.aria-label]="'ai-assistant.detail.show' | translate" [matTooltip]="'ai-assistant.detail.show' | translate" matTooltipPosition="above">
<mat-icon class="tb-mat-16" aria-hidden="true">visibility</mat-icon>
</button>
} @else {
{{ factValue(fact) }}
}
</dd>
}
</dl>
}
@case ('list') {
@if (block.label) {
<div class="k-detail-label">{{ say(block.label) }}</div>
}
<ul class="k-made">
@for (row of block.rows; track $index) {
<li>{{ rowText(row) }}</li>
}
</ul>
}
@case ('commands') {
<div class="k-codetabs-slot" [attr.data-block]="$index"></div>
}
@case ('code') {
@if (block.title) {
<div class="k-detail-label">{{ ('ai-assistant.action.' + block.title) | translate }}</div>
}
<pre><code [class]="'language-' + (block.lang || block.label.toLowerCase())" [attr.data-label]="block.lang ? codeLabel(block.label) : null">{{ block.text }}</code></pre>
}
@case ('links') {
<div class="k-detail-links">
@for (row of block.rows; track $index) {
<a class="k-detail-link" [href]="row.url" target="_blank" rel="noopener">
<span class="k-detail-link-t">{{ row.title }}</span>
<span class="k-detail-link-from">{{ row.from }}</span>
@if (row.snippet) {
<span class="k-detail-link-s">{{ row.snippet }}</span>
}
</a>
}
</div>
}
@case ('markdown') {
<div class="k-detail-md">
<tb-markdown usePlainMarkdown [highlight]="false" [data]="block.text"></tb-markdown>
</div>
}
@case ('images') {
<div class="k-detail-images">
@for (image of block.rows; track image.url) {
<figure>
<img tbAiFadeIn [src]="image.url | image: {preview: true, ignoreLoadingImage: true} | async" [alt]="image.label ? say(image.label) : ''">
@if (image.label) {
<figcaption>{{ say(image.label) }}</figcaption>
}
</figure>
}
</div>
}
@case ('note') {
<p class="k-detail-note">{{ say(block.text) }}</p>
}
@case ('text') {
<p class="k-detail-text">{{ block.text }}</p>
}
@case ('json') {
<div class="k-detail-label">{{ ('ai-assistant.action.' + block.label) | translate }}</div>
<pre class="k-detail-json"><code class="language-json">{{ block.text }}</code></pre>
}
}
}
<ng-template #moreToggle let-key="key" let-count="count">
<button type="button" class="tb-ai-more" [attr.aria-expanded]="isOpen(key)" (click)="toggleMore(key)">
<mat-icon class="tb-mat-16" aria-hidden="true">{{ isOpen(key) ? 'expand_less' : 'expand_more' }}</mat-icon>
{{ isOpen(key) ? ('ai-assistant.summary.fewer' | translate) : ('ai-assistant.summary.more' | translate: {count}) }}
</button>
</ng-template>

271
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<string>([
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<AiDetailView>();
names = input<AiDetailNames>(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<HTMLElement>);
private clipboard = inject(ClipboardService);
private fetched = signal<ReadonlyMap<string, string>>(new Map());
private hubItems = signal<ReadonlyMap<string, MpItemVersionView>>(new Map());
revealed = signal<ReadonlySet<string>>(new Set());
readonly LIST_SHOWN = 8;
private opened = signal<ReadonlySet<string>>(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<T>(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<AiRecordView[]>(() => {
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<string, string | number> = {};
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<string, string>();
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);
});
}
}

2263
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts

File diff suppressed because it is too large

43
ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html

@ -0,0 +1,43 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
@switch (action().status) {
@case ('RUNNING') {
<tb-ai-work-line [words]="running()" [kind]="words().kind" [since]="action().startedAt"></tb-ai-work-line>
}
@case ('STOPPED') {
<tb-ai-work-line [words]="running()" kind="stop" [held]="true"></tb-ai-work-line>
}
@default {
<div class="out">
<mat-icon class="mark" aria-hidden="true">{{ action().status === 'FAILURE' ? 'error_outline' : 'check' }}</mat-icon>
<span class="say">@if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {<a class="tb-chiplink" [routerLink]="chip.link"><code class="k-ent" [attr.data-pal]="chip.palette"><span class="mat-icon notranslate material-icons mat-ligature-font k-ent-ic" aria-hidden="true">{{ chip.icon }}</span>{{ chip.name }}<span class="mat-icon notranslate material-icons mat-ligature-font tb-chip-go" aria-hidden="true">chevron_right</span></code></a>} @else {<code class="k-ent" [attr.data-pal]="chip.palette"><span class="mat-icon notranslate material-icons mat-ligature-font k-ent-ic" aria-hidden="true">{{ chip.icon }}</span>{{ chip.name }}</code>}{{ chip.after }}} @else {{{ outcome() }}}</span>
@if (duration()) {
<span class="dur">{{ duration() }}</span>
}
</div>
@if (arrival()?.readings?.length) {
<div class="k-arrived">
@for (reading of arrival().readings; track reading.key) {
<span class="k-reading"><code>{{ reading.key }}</code><b>{{ reading.value }}</b></span>
}
</div>
}
@if (listing(); as hub) {
<div class="k-recs k-out-recs">
<tb-ai-record [entityType]="hub.entityType" [alarmRule]="hub.alarmRule" [name]="hub.name" [url]="hub.url" [hub]="hub.hub"></tb-ai-record>
</div>
}
@if (hasDetails()) {
<tb-ai-disclosure class="action-details" variant="details" [summary]="'ai-assistant.action.details' | translate" [key]="'action:' + action().executionId">
@if (records().length) {
<tb-ai-run-summary class="records" [entities]="records()"></tb-ai-run-summary>
}
<tb-ai-action-detail [view]="detail()" [names]="names()"></tb-ai-action-detail>
</tb-ai-disclosure>
}
}
}

95
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);
}
}

185
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<AiAction>();
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<string>();
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<AiDetailNames>(new Map());
facts = input<AiDetailFact[]>([]);
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;
}
}

817
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<string, string | AiWordList>;
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<string, string> = {
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<string, string> = {
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<string, [string, string]> = {
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<string, string> = {
DEVICE: 'search-devices',
ASSET: 'search-assets',
DASHBOARD: 'search-dashboards',
CUSTOMER: 'search-customers',
USER: 'search-users'
};
const DELETED_TARGETS: Record<string, string> = {
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<string, unknown>;
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<string, unknown> | 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<string, any>;
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<string, string> = {
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<string, string> = {};
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, any>): 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<string, any>;
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, any>): string {
const filter = values.entityFilter ?? values;
const types = new Set<string>();
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, any>): 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<string, AiEntityKind> = {
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'};
}

155
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') {
<div class="approval-title">{{ data.title ?? ('ai-assistant.action-approval-required' | translate) }}</div>
<div class="approval-content">{{ data.message }}</div>
<div class="approval-actions">
<button mat-stroked-button class="denied" (click)="deny()">
<mat-icon>block</mat-icon>
{{ data.denyLabel ?? ('ai-assistant.deny' | translate) }}
</button>
<button mat-flat-button [class.approved]="!isDestructive" [class.danger]="isDestructive" (click)="approve()">
<mat-icon>{{ approveIcon }}</mat-icon>
{{ data.approveLabel ?? ('ai-assistant.approve' | translate) }}
</button>
</div>
<button mat-button class="approve-all" (click)="approveAll()">
<mat-icon>done_all</mat-icon>
{{ 'ai-assistant.approve-all' | translate }}
</button>
@if (handedOver) {
<tb-ai-action-line [action]="handedOver" [outcomeText]="outcomeText" [autoApproved]="state === 'auto'" [linkEntity]="!isDestructive" [facts]="handedFacts"></tb-ai-action-line>
} @else {
<div class="k-review"
[class.done]="state === 'approved'"
[class.auto]="state === 'auto'"
[class.denied]="state === 'denied'"
[class.expired]="state === 'expired'"
[class.danger]="isDestructive">
<div class="k-head"><mat-icon aria-hidden="true">{{ headIcon }}</mat-icon>{{ headText }}</div>
@if (listing; as hub) {
<tb-ai-record [entityType]="hub.entityType" [alarmRule]="hub.alarmRule" [name]="hub.name" [url]="hub.url" [hub]="hub.hub"
[class.closed]="recordClosed"></tb-ai-record>
} @else if (review) {
<tb-ai-record [entityType]="review.entityType" [alarmRule]="alarmRule" [name]="recordName" [meta]="meta"
[class.closed]="recordClosed" [class.planned]="planned"></tb-ai-record>
}
@case ('executing') {
<div class="approval-result">
<mat-progress-spinner mode="indeterminate" diameter="20"></mat-progress-spinner>
<span class="flex-1">{{ data.executing ?? ('ai-assistant.processing' | translate) }}</span>
</div>
@switch (state) {
@case ('pending') {
@if (!review) {
<p class="k-review-p">{{ data.message }}</p>
}
@if (facts.length) {
<dl class="k-fields">
@for (fact of facts; track $index) {
<dt>@if (fact.labelCode) { <code>{{ fact.label }}</code> } @else { {{ fact.label }} }</dt>
<dd>@if (fact.chip; as chip) { <span class="k-fact-chip">@if (chip.image) { <img [src]="chip.image" alt="" aria-hidden="true"> } @else if (chip.icon) { <mat-icon class="tb-mat-16" aria-hidden="true">{{ chip.icon }}</mat-icon> }{{ fact.value }}</span> } @else if (fact.image) { <img tbAiFadeIn class="k-img" [src]="fact.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else if (fact.valueCode) { <code>{{ fact.value }}</code> } @else { {{ fact.value }} }</dd>
}
</dl>
}
@for (block of codeBlocks; track $index) {
@if (block.current !== undefined) {
<div class="k-review-code"><pre><code [class]="'language-' + block.lang" [attr.data-label]="block.label + ' · ' + ('ai-assistant.review.current' | translate)">{{ block.current }}</code></pre></div>
}
<div class="k-review-code"><pre><code [class]="'language-' + block.lang" [attr.data-nocopy]="block.lang === 'diff' ? '' : null" [attr.data-label]="block.current !== undefined ? block.label + ' · ' + ('ai-assistant.review.new' | translate) : block.label">{{ block.value }}</code></pre></div>
}
@if (changes.length) {
<table class="k-diff" [class.k-diff-stacked]="stackedDiff">
<thead>
<tr>
<td></td>
<th scope="col">{{ 'ai-assistant.review.current' | translate }}</th>
<th scope="col">{{ 'ai-assistant.review.new' | translate }}</th>
</tr>
</thead>
<tbody>
@for (change of changes; track $index) {
<tr>
<th scope="row">@if (change.labelCode) { <code>{{ change.label }}</code> } @else { {{ change.label }} }</th>
@if (change.image || change.currentImage) {
<td class="k-diff-was">
@if (change.currentImage) { <img tbAiFadeIn class="k-img was" [src]="change.current | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { {{ change.current }} }
</td>
<td class="k-diff-now">
@if (change.image) { <img tbAiFadeIn class="k-img" [src]="change.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { <span>{{ change.value }}</span> }
</td>
} @else {
<td class="k-diff-was">{{ change.current }}</td>
<td class="k-diff-now"><span>{{ change.value }}</span></td>
}
</tr>
}
</tbody>
@if (unchanged.length && showUnchanged) {
<tbody class="k-diff-same">
@for (same of unchanged; track $index) {
<tr>
<th scope="row">@if (same.labelCode) { <code>{{ same.label }}</code> } @else { {{ same.label }} }</th>
<td colspan="2">{{ same.value }}</td>
</tr>
}
</tbody>
}
</table>
@if (unchanged.length) {
<button type="button" class="tb-ai-more" [attr.aria-expanded]="showUnchanged" (click)="toggleUnchanged()">
<mat-icon aria-hidden="true">{{ showUnchanged ? 'expand_less' : 'expand_more' }}</mat-icon>
{{ (showUnchanged ? 'ai-assistant.review.hide-unchanged' : 'ai-assistant.review.unchanged') | translate: {count: unchanged.length} }}
</button>
}
}
<div class="k-actions">
<button mat-flat-button type="button" [class.warn]="isDestructive" (click)="approve()">
<mat-icon>{{ isDestructive ? 'delete' : 'check' }}</mat-icon>
{{ approveLabel | translate }}
</button>
<button mat-button type="button" (click)="deny()">
<mat-icon>close</mat-icon>
{{ 'ai-assistant.deny' | translate }}
</button>
</div>
@if (denying) {
<div class="k-deny">
<input #denyInput class="k-deny-in" type="text" maxlength="2000" spellcheck="false"
[placeholder]="'ai-assistant.what-should-be-different' | translate"
[attr.aria-label]="'ai-assistant.what-should-be-different' | translate"
(keydown.enter)="$event.preventDefault(); sendDeny(denyInput.value)"
(keydown.escape)="$event.stopPropagation(); closeDeny()">
</div>
}
}
@case ('denied') {
<p class="k-review-p">{{ 'ai-assistant.review.denied-text' | translate }}</p>
}
@case ('expired') {
<p class="k-review-p">{{ 'ai-assistant.review.expired-text' | translate }}</p>
<div class="k-actions">
<button mat-stroked-button type="button" (click)="askAgain.emit()">
<mat-icon>refresh</mat-icon>
{{ 'ai-assistant.review.ask-again' | translate }}
</button>
</div>
}
}
@case ('approved') {
<div class="approval-result">
<mat-icon>{{ resultIcon }}</mat-icon>
<span class="flex-1">{{ completedExecution?.message || ('ai-assistant.approved' | translate) }}</span>
</div>
}
@case ('denied') {
<div class="approval-result">
<mat-icon>{{ resultIcon }}</mat-icon>
<span class="flex-1">{{ completedExecution?.message || ('ai-assistant.denied' | translate) }}</span>
</div>
}
@case ('error') {
<div class="approval-result">
<mat-icon>{{ resultIcon }}</mat-icon>
<span class="flex-1">{{ completedExecution?.message || ('ai-assistant.error' | translate) }}</span>
</div>
@if (data.time) {
<time class="k-time" [attr.datetime]="data.time | date:'yyyy-MM-ddTHH:mm:ss'">{{ data.time | date:'HH:mm' }}</time>
}
</div>
}

78
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;
}
}

445
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<string, string[]> = {
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<string, string> = {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<string>([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<HTMLInputElement>;
@Output() approvalAction = new EventEmitter<ApprovalResult>();
@HostBinding('class') state: ApprovalCardState = 'pending';
@Output() askAgain = new EventEmitter<void>();
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<HTMLElement>);
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;
}
}

23
ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html

@ -0,0 +1,23 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="art-pane-edge" role="separator" tabindex="0" aria-orientation="vertical"
[attr.aria-label]="'ai-assistant.artifact.resize' | translate"
[matTooltip]="'ai-assistant.artifact.resize-hint' | translate" matTooltipPosition="left" matTooltipShowDelay="600"
(pointerdown)="startResize($event)" (dblclick)="resetWidth()" (keydown)="onEdgeKey($event)"></div>
<div class="art-pane-head">
<button type="button" class="art-ib art-pane-close" (click)="closed.emit()"
[matTooltip]="'ai-assistant.artifact.close' | translate" matTooltipPosition="below"
[attr.aria-label]="'ai-assistant.artifact.close' | translate">
<mat-icon class="wide-only">chevron_right</mat-icon>
<mat-icon class="narrow-only">arrow_back</mat-icon>
</button>
<ng-content select="[artHead]"></ng-content>
</div>
<div #body class="art-pane-body" [class.dark]="dark()" (scroll)="refreshEdges()">
<ng-content></ng-content>
</div>
<ng-content select="[artFoot]"></ng-content>

134
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<void>();
@ViewChild('body', {static: true}) body: ElementRef<HTMLElement>;
width = signal<number | null>(AiArtifactPaneComponent.storedWidth());
scrolled = signal(false);
more = signal(false);
private host = inject(ElementRef<HTMLElement>);
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);
}
}

253
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();
<button #aiButton tb-ai-mark class="tb-ai-assistant-button" [cue]="markCue()"
[working]="status?.level === 'running'" [glow]="introOpen()"
tb-popover [tbAiTip]="buttonTip" [tbPopoverTrigger]="introOpen() ? null : 'hover'"
[attr.aria-label]="status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate)"
aria-keyshortcuts="/"
(click)="toggle($event)">
</button>
<ng-template #buttonTip>
<div class="tb-ai-tip-body tip-mini">
<div class="tip-keyrow">
<span>{{ status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate) }}</span>
<span class="tip-caps"><kbd>/</kbd></span>
</div>
</div>
</ng-template>
}
`,
styles: [`
:host {
display: contents;
}
`],
standalone: false,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AiAssistantButtonComponent {
panelService = inject(AiAssistantPanelService);
private store = inject(Store<AppState>);
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<HTMLElement>});
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<typeof setTimeout> | 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<AiMarkCue | null>(() => {
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);
}
}

58
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<AiChatClientContext | undefined>(() => {
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 '';
}
}
}

126
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html

@ -4,105 +4,29 @@
SPDX-License-Identifier: BUSL-1.1
-->
<div #chatContainer class="ai-assistant-container relative"
[class.fill]="panelService.detailsOpen() || !!panelService.config()?.fill"
[class.details-open]="panelService.detailsOpen()">
<div class="ai-assistant-header">
<button mat-button [matMenuTriggerFor]="chatMenu" #chatTriggerEl class="chat-selector"
(menuOpened)="setMenuWidth(chatTriggerEl)">
{{ selectedChatTitle() || ('ai-assistant.new-chat' | translate) }}
<mat-icon iconPositionEnd>keyboard_arrow_down</mat-icon>
</button>
<mat-menu #chatMenu="matMenu" class="ai-chat-list-menu">
<ng-template matMenuContent>
@for (group of groupedChats(); track group.label) {
<div class="chat-group-label">{{ group.label | translate }}</div>
@for (chat of group.chats; track chat.id) {
<button mat-menu-item class="chat-item" [class.selected]="chat.id === chatId()" (click)="selectChat(chat)">
{{ chat.title }}
</button>
}
} @empty {
<div class="chat-group-empty">{{ 'ai-assistant.no-chats' | translate }}</div>
}
</ng-template>
</mat-menu>
<div class="flex items-center">
<button mat-icon-button [matMenuTriggerFor]="chatActionsMenu" [class.invisible]="!chatId()"
matTooltip="{{ 'action.more' | translate }}"
matTooltipPosition="above">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #chatActionsMenu="matMenu" class="ai-chat-action-menu">
<button mat-menu-item (click)="renameChat()">
<mat-icon>edit</mat-icon>
<span>{{ 'action.rename' | translate }}</span>
</button>
<button mat-menu-item class="delete" (click)="deleteChat()">
<mat-icon>delete</mat-icon>
<span>{{ 'action.delete' | translate }}</span>
</button>
</mat-menu>
<tb-ai-credits [asButton]="true" [active]="slideDone()"></tb-ai-credits>
<button mat-icon-button (click)="reset(true)"
matTooltip="{{ 'ai-assistant.new-chat' | translate }}"
matTooltipPosition="above">
<tb-icon>mdi:square-edit-outline</tb-icon>
</button>
<button mat-icon-button (click)="close()"
matTooltip="{{ 'action.close' | translate }}"
matTooltipPosition="above">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
<div class="ai-assistant-content">
@if (messages().length) {
<div class="chat-messages-container">
<div tb-toast toastTarget="aiAssistant" class="pointer-events-none absolute inset-0"></div>
<tb-ai-chat-messages
class="ai-chat-messages"
[messages]="messages()"
[loading]="loading()"
[completedExecutions]="completedExecutions()"
[autoApprove]="autoApprove()"
[additionalStyles]="['.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 {padding-inline-start: 30px;} .tb-markdown-view ul{padding-left: 28px;padding-right:0}'
]"
(approvalAction)="onApprovalAction($event)"
(resourceError)="showErrorMessage($event)">
</tb-ai-chat-messages>
</div>
} @else {
<div class="relative flex flex-auto justify-center">
<div tb-toast toastTarget="aiAssistant" class="pointer-events-none absolute inset-0"></div>
<div class="flex flex-col items-center justify-center gap-6">
<svg class="image-main-color" preserveAspectRatio="xMidYMid meet" viewBox="0 0 42 48" width="70px">
<use [attr.xlink:href]="'/assets/solution-creator/iot-assistant.svg#iot-assistant'"></use>
</svg>
<div class="flex flex-col gap-1">
<div class="whitespace-pre-line text-center text-xl font-semibold" translate>ai-assistant.main-title</div>
<div class="whitespace-pre-line text-center leading-6">{{ subTitle() }}</div>
</div>
</div>
</div>
}
@if (!messages().length && promptExamples().length) {
<div class="example-chips">
@for (example of promptExamples(); track example.message) {
<button type="button" mat-stroked-button class="example-chip" (click)="useExample(example)">
{{ example.label }}
</button>
}
</div>
}
</div>
<tb-ai-prompt-input
class="ai-assistant-composer"
[docked]="true"
[placeholder]="activePlaceholder()"
[loading]="loading()"
[dropZone]="chatContainer"
(messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input>
<div #gripTip class="tb-ai-grip" role="separator" tabindex="0" aria-orientation="vertical"
[attr.aria-label]="'ai-assistant.resize-panel' | translate"
[matTooltip]="'ai-assistant.resize-panel-hint' | translate" matTooltipPosition="left" [matTooltipDisabled]="resizing()"
[attr.aria-valuemin]="minWidth" [attr.aria-valuemax]="splitAvailable() ? splitWidth() : maxWidth" [attr.aria-valuenow]="width()"
(dblclick)="setWidth(defaultWidth, true)"
(keydown)="onGripKey($event)"
(pointerdown)="startResize($event)"></div>
<div class="ai-assistant-container">
<tb-ai-chat class="ai-assistant-chat"
variant="panel"
toastTarget="aiAssistant"
[fullscreenEnabled]="false"
[chatId]="chatId()"
(chatIdChange)="onChatId($event)"
[clientContext]="clientContext()"
[prompts]="welcome().examples"
[startTitle]="welcome().title"
[startLine]="welcome().line"
[startPlaceholder]="panelService.config()?.initialPromptPlaceholder"
[startSuggestion]="welcome().suggestion"
[split]="split()"
[splitAvailable]="splitAvailable()"
(splitToggle)="toggleSplit()"
(closed)="close()">
</tb-ai-chat>
</div>

247
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);
}
}
}

674
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<boolean>(false);
readonly defaultWidth = 364;
loading = signal<boolean>(false);
readonly minWidth = 320;
isCreatingNew = signal<boolean>(false);
readonly maxWidth = 480;
messages = signal<ChatMessage[]>([]);
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<Record<string, ToolExecutionResult>>({});
width = signal(this.defaultWidth);
chatId = signal<string | undefined>(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<AiAssistantPromptExample[]>(() => 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<ChatGroup[]>(() => {
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<string | undefined>(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<AppState>);
private destroyRef = inject(DestroyRef);
private sanitizer = inject(DomSanitizer);
private chats = inject(AiChatsService);
private elementRef = inject(ElementRef<HTMLElement>);
private loadChat$ = new Subject<string>();
private cancelMessage$ = new Subject<void>();
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, AiRenameDialogData, string>(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<typeof setTimeout> | 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<ChatEvent> {
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<string, ToolExecutionResult> = {};
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<ChatEvent> {
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<ChatEvent> {
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'
}));
}
}

23
ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html

@ -5,12 +5,23 @@
-->
<mat-toolbar class="flex items-center gap-2">
<h2 class="preview-title">{{ data.resource.name }}</h2>
<h2 class="preview-title">{{ title }}</h2>
<span class="flex-1"></span>
<button mat-icon-button type="button" (click)="download()"
[matTooltip]="'action.download' | translate" matTooltipPosition="above">
<mat-icon>download</mat-icon>
</button>
@if (data.downloadPng) {
<button mat-icon-button type="button" [matMenuTriggerFor]="downloads"
[matTooltip]="'action.download' | translate" matTooltipPosition="above">
<mat-icon>download</mat-icon>
</button>
<mat-menu #downloads="matMenu" xPosition="before">
<button mat-menu-item type="button" (click)="download()">{{ 'ai-assistant.file.download-svg' | translate }}</button>
<button mat-menu-item type="button" (click)="downloadPng()">{{ 'ai-assistant.file.download-png' | translate }}</button>
</mat-menu>
} @else {
<button mat-icon-button type="button" (click)="download()"
[matTooltip]="'action.download' | translate" matTooltipPosition="above">
<mat-icon>download</mat-icon>
</button>
}
<button mat-icon-button type="button" (click)="close()"
[matTooltip]="'action.close' | translate" matTooltipPosition="above">
<mat-icon>close</mat-icon>
@ -19,7 +30,7 @@
<div mat-dialog-content class="preview-content" tb-toast toastTarget="aiAttachmentPreview">
@if (preview$ | async; as preview) {
@if (preview.url) {
<img [src]="preview.url" [alt]="data.resource.name">
<img tbAiFadeIn [src]="preview.url" [alt]="title" [class.vector]="data.vector">
} @else {
<div class="preview-error">
<mat-icon>broken_image</mat-icon>

5
ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss

@ -27,6 +27,11 @@
max-height: calc(90vh - 96px);
object-fit: contain;
border-radius: 8px;
&.vector {
width: min(1200px, 88vw);
height: auto;
}
}
.preview-error {

26
ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts

@ -17,7 +17,12 @@ import { AiResourceService } from '@core/http/ai-resource.service';
import { AiResourceInfo } from '@shared/models/ai-chat.models';
export interface AiAttachmentPreviewDialogData {
resource: AiResourceInfo;
resource?: AiResourceInfo;
name?: string;
url?: string;
vector?: boolean;
download?: () => void;
downloadPng?: () => Promise<void>;
}
interface AiAttachmentPreview {
@ -34,6 +39,7 @@ interface AiAttachmentPreview {
export class AiAttachmentPreviewDialogComponent extends DialogComponent<AiAttachmentPreviewDialogComponent> {
readonly preview$: Observable<AiAttachmentPreview>;
readonly title: string;
constructor(protected store: Store<AppState>,
protected router: Router,
@ -43,13 +49,18 @@ export class AiAttachmentPreviewDialogComponent extends DialogComponent<AiAttach
private translate: TranslateService,
private sanitizer: DomSanitizer) {
super(store, router, dialogRef);
this.preview$ = this.aiResourceService.getUrl(data.resource.id).pipe(
this.title = data.resource?.name ?? data.name;
this.preview$ = data.url ? of({url: data.url}) : this.aiResourceService.getUrl(data.resource.id).pipe(
map(url => ({url})),
catchError(error => of({error: this.errorMessage(error)}))
);
}
download(): void {
if (this.data.download) {
this.data.download();
return;
}
this.aiResourceService.download(this.data.resource).subscribe({
error: error => this.store.dispatch(new ActionNotificationShow({
message: this.errorMessage(error),
@ -62,6 +73,17 @@ export class AiAttachmentPreviewDialogComponent extends DialogComponent<AiAttach
});
}
downloadPng(): void {
this.data.downloadPng().catch(() => this.store.dispatch(new ActionNotificationShow({
message: this.translate.instant('ai-assistant.file.png-failed'),
target: 'aiAttachmentPreview',
modern: true,
type: 'error',
verticalPosition: 'bottom',
horizontalPosition: 'center'
})));
}
close(): void {
this.dialogRef.close();
}

19
ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts

@ -1,7 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { HttpErrorResponse } from '@angular/common/http';
import { AI_IMAGE_MEDIA_TYPES } from '@shared/models/ai-chat.models';
import { AI_IMAGE_MEDIA_TYPES, AiResourceFacts } from '@shared/models/ai-chat.models';
import { TranslateService } from '@ngx-translate/core';
const MAX_IMAGE_SIDE = 2560;
const MIN_SVG_SIDE = 1024;
@ -187,3 +188,19 @@ export function aiServerMessage(error: unknown): string | undefined {
const message = body && typeof body === 'object' ? (body as {message?: unknown}).message : undefined;
return typeof message === 'string' && message.trim() ? message.trim() : undefined;
}
export function aiResourceFact(facts: AiResourceFacts | undefined, translate: TranslateService): string | null {
if (!facts) {
return null;
}
if (facts.pages != null) {
return translate.instant('ai-assistant.fact.pages', {count: facts.pages});
}
if (facts.rows != null) {
return translate.instant('ai-assistant.fact.rows', {count: facts.rows}) + ' · ' + translate.instant('ai-assistant.fact.columns', {count: facts.columns ?? 0});
}
if (facts.lines != null) {
return translate.instant('ai-assistant.fact.lines', {count: facts.lines});
}
return null;
}

31
ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html

@ -4,27 +4,22 @@
SPDX-License-Identifier: BUSL-1.1
-->
<div class="attachments">
<div class="k-files">
@for (item of shown; track item.resource.id) {
<div class="attachment"
[class.image]="item.image"
[class.file]="!item.image"
[matTooltip]="item.resource.name"
matTooltipPosition="above"
(click)="open(item)">
<button type="button" class="k-file" [class.pic]="item.image" [matTooltip]="item.resource.name" matTooltipPosition="above" (click)="open(item)">
@if (item.image) {
@if (item.url$ | async; as url) {
<img [src]="url" [alt]="item.resource.name">
} @else {
<mat-icon class="placeholder">image</mat-icon>
}
<span class="k-file-pic" aria-hidden="true">
@if (item.url$ | async; as url) {
<img tbAiFadeIn [src]="url" alt="">
}
</span>
} @else {
<div class="file-icon"><mat-icon>{{ item.icon }}</mat-icon></div>
<div class="file-meta">
<span class="file-name">{{ item.resource.name }}</span>
<span class="file-info">{{ item.extension }}@if (item.extension) { · }{{ item.resource.size | fileSize }}</span>
</div>
<mat-icon class="tb-mat-18" aria-hidden="true">{{ item.icon }}</mat-icon>
}
</div>
<span class="k-file-text">
<b><span class="art-name">{{ fileName(item.resource.name).base }}<span class="art-ext">{{ fileName(item.resource.name).ext }}</span></span></b>
<small>@if (!item.image && item.extension) { {{ item.extension }} · }{{ factOf(item) ?? (item.resource.size | fileSize) }}</small>
</span>
</button>
}
</div>

154
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);
}
}

13
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<any>();
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 {

52
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) {
<button type="button" class="ob-chip" [class.k-chip-quiet]="action.quiet" [class.k-chip-compose]="!!action.compose"
[attr.aria-pressed]="action.pressed ?? null"
[matTooltip]="action.tip ?? ''" [matTooltipDisabled]="!action.tip" matTooltipPosition="above"
(click)="press(action)">
@if (action.icon) {
<mat-icon aria-hidden="true">{{ action.icon }}</mat-icon>
}
{{ action.label }}
</button>
}
`,
standalone: false,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'k-chips',
'role': 'group'
}
})
export class AiCardActionsComponent {
actions = input.required<AiCardAction[]>();
act = output<string>();
compose = output<string>();
press(action: AiCardAction): void {
if (action.compose) {
this.compose.emit(action.compose);
} else {
this.act.emit(action.id);
}
}
}

280
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) {
<div class="k-day" role="separator"><span>{{ day }}</span></div>
}
@if (msg.from === 'USER' && (msg.answers?.length || answersAt[$index])) {
<tb-ai-question class="answers" [questions]="[]" [answered]="msg.answers ?? answersAt[$index]" [time]="msg.time"></tb-ai-question>
} @else if (msg.from === 'USER') {
@if (msg.startedFrom) {
<tb-ai-started-from [from]="msg.startedFrom"></tb-ai-started-from>
}
<div class="user">
@if (msg.resources?.length) {
<tb-ai-attachments class="user-attachments" [resources]="msg.resources"
(resourceError)="resourceError.emit($event)"></tb-ai-attachments>
}
@if (msg.content) {
<div class="msg">{{ msg.content }}</div>
<div class="turn">
@if (quotes[$index]; as quoted) {
<span class="k-quote-chip">
<mat-icon class="tb-mat-18" aria-hidden="true">{{ quoted.icon }}</mat-icon>
<span><b><span class="art-name">{{ fileName(quoted.name).base }}<span class="art-ext">{{ fileName(quoted.name).ext }}</span></span></b><small>{{ (quoted.from === quoted.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: quoted.from, to: quoted.to} }}</small></span>
</span>
}
@if (quotes[$index] ? quotes[$index].message : msg.content; as words) {
<div class="msg" [class.folded]="isFolded($index, words)"><span class="words">{{ words }}</span></div>
@if (isFolded($index, words)) {
<button type="button" class="tb-ai-more show-all" (click)="unfold($index)">
<mat-icon aria-hidden="true">expand_more</mat-icon>{{ 'ai-assistant.show-all' | translate }}
</button>
}
}
@if (msg.resources?.length) {
<tb-ai-attachments [resources]="msg.resources" (resourceError)="resourceError.emit($event)"></tb-ai-attachments>
}
</div>
<div class="msg-foot user-foot">
@if (msg.content) {
<span class="foot-tools">
<button type="button" class="foot-tool" [class.done]="copiedIndex === $index"
[matTooltip]="(copiedIndex === $index ? 'ai-assistant.copied' : 'ai-assistant.copy') | translate"
matTooltipPosition="above" [attr.aria-label]="'ai-assistant.copy' | translate"
(click)="copyText(msg.content, $index)">
<mat-icon class="tb-mat-16">{{ copiedIndex === $index ? 'check' : 'content_copy' }}</mat-icon>
</button>
<button type="button" class="foot-tool" [matTooltip]="'ai-assistant.edit-message' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.edit-message' | translate" (click)="editMessage.emit(quotes[$index]?.message ?? msg.content)">
<mat-icon class="tb-mat-16">edit</mat-icon>
</button>
</span>
}
@if (msg.time) {
<time [matTooltip]="fullTime(msg.time)" matTooltipPosition="above">{{ msg.time | date:'HH:mm' }}</time>
}
</div>
</div>
} @else if (msg.from === 'ACTION' && files[$index] && inCard.has(files[$index].name)) {
} @else if (msg.from === 'ACTION' && files[$index]; as file) {
<div class="ai art-cards">
<button type="button" class="art-card" [class.on]="shownFile === file.executionId" [attr.aria-pressed]="shownFile === file.executionId"
(click)="openFile.emit(file)">
<span class="art-card-ic"><mat-icon class="tb-mat-20" aria-hidden="true">{{ fileMark(file) }}</mat-icon></span>
<span class="art-card-t"><b><span class="art-name">{{ fileName(file.name).base }}<span class="art-ext">{{ fileName(file.name).ext }}</span></span></b>
<small>{{ 'ai-assistant.file.lines' | translate: {count: file.lines} }} · {{ file.size }}@if (file.edited) {<span class="art-card-ed">{{ 'ai-assistant.file.edited' | translate }}</span>}</small></span>
<mat-icon class="tb-mat-18 art-card-chev" aria-hidden="true">chevron_right</mat-icon>
</button>
</div>
} @else if (msg.from === 'ACTION' && madeFiles[$index]; as made) {
<div class="ai art-cards">
<div class="art-card made">
<button type="button" class="art-card-open" (click)="openMadeFile(made)"
[attr.aria-label]="(made.preview ? 'ai-assistant.file.open' : 'ai-assistant.file.download') | translate">
<span class="art-card-ic"><mat-icon class="tb-mat-20" aria-hidden="true">{{ made.icon }}</mat-icon></span>
<span class="art-card-t"><b><span class="art-name">{{ fileName(made.resource.name).base }}<span class="art-ext">{{ fileName(made.resource.name).ext }}</span></span></b><small>{{ made.size }}</small></span>
</button>
<button type="button" class="art-card-dl" (click)="downloadMadeFile(made)"
[matTooltip]="'ai-assistant.file.download' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.download' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">download</mat-icon>
</button>
</div>
</div>
} @else if (msg.from === 'ACTION' && plans[$index]; as plan) {
<div class="ai plan">
<tb-ai-plan [steps]="plan.steps" [progress]="plan.progress" [gate]="plan.gate" [autoApprove]="autoApprove"
(run)="runPlan.emit({run: $event, steps: plan.steps})" (change)="changePlan.emit()"></tb-ai-plan>
</div>
} @else if (msg.from === 'ACTION' && handOvers[$index]; as card) {
<div class="ai hand">
<tb-ai-hand-over [handOver]="card.handOver" [wait]="card.wait" [time]="msg.data.startedAt" (prompt)="prompt.emit($event)" (stop)="stopRun.emit()" (compose)="compose.emit($event)"
[files]="latestFiles" (openFile)="openFile.emit($event)"></tb-ai-hand-over>
</div>
@if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) {
@if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) {
<div class="ai action">
<tb-ai-action-line [action]="moved.data" [names]="detailNames" [more]="0"></tb-ai-action-line>
</div>
}
}
} @else if (msg.from === 'ACTION' && asking?.index === $index) {
<div class="ai ask">
<tb-ai-question [questions]="asking.questions" [time]="msg.data.startedAt" (done)="answerQuestions($event)" (skip)="answerQuestions($event)"></tb-ai-question>
</div>
} @else if (msg.from === 'ACTION') {
@if (isListedAction(msg, $index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) {
<div class="ai action">
<tb-ai-action-line [action]="msg.data" [names]="detailNames" [more]="$index === runningLead ? runningCount - 1 : 0"></tb-ai-action-line>
@if ($index === retryIndex) {
<div class="k-actions action-ways">
<button mat-stroked-button type="button" (click)="prompt.emit(retryPrompt)">
<mat-icon>replay</mat-icon>{{ 'ai-assistant.action.try-again' | translate }}
</button>
</div>
}
</div>
}
} @else {
<div class="ai">
@if ($index === offerIndex) {
<div class="ai">
<div class="k-offer" role="group" [attr.aria-label]="'ai-assistant.offer.label' | translate">
<span class="k-offer-ic" aria-hidden="true"><mat-icon>bolt</mat-icon></span>
<span>{{ 'ai-assistant.offer.text' | translate }}</span>
<tb-ai-card-actions [actions]="offerActions()" (act)="offerAct($event)"></tb-ai-card-actions>
</div>
</div>
}
<div class="ai" [class.action]="msg.from === 'APPROVAL' && getCompletedExecution(msg)?.approvalStatus === 'APPROVED'">
@if (msg.from === 'APPROVAL') {
<tb-ai-approval-card
[data]="getApprovalData(msg)"
[completedExecution]="getCompletedExecution(msg)"
[autoApprove]="autoApprove"
(approvalAction)="approval($event)">
[answered]="!!denyReasons[getApprovalData(msg).executionId]"
(approvalAction)="approval($event)"
(askAgain)="askAgain.emit()">
</tb-ai-approval-card>
} @else if (msg.status === 'INCOMPLETE') {
<div class="incomplete flex items-start gap-2">
} @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') {
<div class="incomplete flex" role="status">
<mat-icon class="incomplete-icon">warning_amber</mat-icon>
<span>{{ msg.content }}</span>
<span>{{ msg.status === 'STOPPED' ? stoppedText($index, msg.content) : msg.content }}</span>
</div>
@if (summaries[$index]; as entities) {
<tb-ai-run-summary class="summary" [entities]="entities"></tb-ai-run-summary>
}
@if (msg.status === 'STOPPED' && $last && !loading) {
<tb-ai-card-actions [actions]="resumeActions()" (act)="resume.emit()"></tb-ai-card-actions>
}
} @else {
<tb-markdown usePlainMarkdown [additionalStyles]="additionalStyles" [data]="parseResult(msg.content)"></tb-markdown>
<div class="agent" [class.done]="msg.done" [class.streaming]="msg.streaming" #answer>
@if (msg.done) {
<mat-icon class="done-mark" aria-hidden="true">check</mat-icon>
}
<div class="agent-body">
@if (msg.lead) {
<p class="lead">{{ msg.lead }}</p>
}
@for (key of [decorationKey(msg)]; track key) {
<tb-markdown usePlainMarkdown [highlight]="false" [additionalStyles]="additionalStyles" [data]="parseResult(msg.done !== undefined ? withoutDoneMark(msg.content) : msg.content)" (ready)="decorateCode(answer, msg)"></tb-markdown>
}
@let madeHere = made[$index] ?? [];
@for (shown of records[$index] ?? []; track $index) {
<tb-ai-records class="agent-records" [shown]="shown" [made]="madeHere" (compose)="compose.emit($event)"></tb-ai-records>
}
@if (summaries[$index]; as entities) {
<tb-ai-run-summary [entities]="entities"></tb-ai-run-summary>
}
@if (msg.entities?.length) {
<tb-ai-run-summary class="agent-card" [entities]="msg.entities" [leadMeta]="msg.entitiesMeta ?? null"></tb-ai-run-summary>
}
@if (msg.hint; as hint) {
<div class="k-hint note agent-hint">
<mat-icon aria-hidden="true">info_outline</mat-icon>
<span><b>{{ hint.lead }}</b> {{ hint.text }}</span>
</div>
}
</div>
</div>
@if (msg.note) {
<p class="agent-note">{{ msg.note }}</p>
}
@if (sources[$index]; as cited) {
<div class="k-docs agent-docs">
@for (source of cited; track source.url) {
<div class="tb-rec card source" [class.ext]="source.external">
<div class="tb-rec-row">
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ source.icon }}</mat-icon></span>
<div class="tb-rec-body">
<a class="tb-rec-title" [href]="source.url" target="_blank" rel="noopener noreferrer">{{ source.title }}<span class="tb-ai-sr-only"> {{ 'ai-assistant.opens-new-tab' | translate }}</span></a>
<span class="tb-rec-meta">{{ source.from }}</span>
</div>
<span class="tb-rec-side"><span class="tb-open" aria-hidden="true"><mat-icon class="tb-mat-18">open_in_new</mat-icon></span></span>
</div>
@if (source.quote) {
<div class="tb-rec-det"><q class="tb-rec-note">{{ source.quote }}</q></div>
}
</div>
}
</div>
}
@if (!msg.streaming) {
<div class="msg-foot agent-foot">
@if (msg.time) {
<time [matTooltip]="fullTime(msg.time)" matTooltipPosition="above">{{ msg.time | date:'HH:mm' }}</time>
}
<span class="foot-tools" [class.show]="$index === lastAnswerIndex">
<button type="button" class="foot-tool" [class.done]="copiedIndex === $index"
[matTooltip]="(copiedIndex === $index ? 'ai-assistant.copied' : 'ai-assistant.copy-answer') | translate"
matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.copy-answer' | translate"
(click)="copyAnswer(answer, $index)">
<mat-icon class="tb-mat-16">{{ copiedIndex === $index ? 'check' : 'content_copy' }}</mat-icon>
</button>
@if (feedback) {
<button type="button" class="foot-tool" [attr.aria-pressed]="msg.rating === 'UP'" [class.muted]="!!msg.rating && msg.rating !== 'UP'"
[matTooltip]="'ai-assistant.feedback.helpful' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.feedback.helpful' | translate" (click)="toggleRating($index, msg.rating, 'UP')">
<mat-icon class="tb-mat-16">{{ msg.rating === 'UP' ? 'thumb_up' : 'thumb_up_off_alt' }}</mat-icon>
</button>
<button type="button" class="foot-tool" [attr.aria-pressed]="msg.rating === 'DOWN'" [class.muted]="!!msg.rating && msg.rating !== 'DOWN'"
[matTooltip]="'ai-assistant.feedback.not-helpful' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.feedback.not-helpful' | translate" (click)="toggleRating($index, msg.rating, 'DOWN')">
<mat-icon class="tb-mat-16">{{ msg.rating === 'DOWN' ? 'thumb_down' : 'thumb_down_off_alt' }}</mat-icon>
</button>
<button type="button" class="foot-tool" [class.done]="msg.reported" [disabled]="msg.reported"
[matTooltip]="(msg.reported ? 'ai-assistant.feedback.reported' : 'ai-assistant.feedback.report') | translate" matTooltipPosition="above"
[attr.aria-label]="(msg.reported ? 'ai-assistant.feedback.reported' : 'ai-assistant.feedback.report') | translate"
[attr.aria-expanded]="reportingIndex === $index" (click)="openReport($index)">
<mat-icon class="tb-mat-16">{{ msg.reported ? 'flag' : 'outlined_flag' }}</mat-icon>
</button>
}
</span>
</div>
}
@if (prompts?.index === $index) {
<div class="k-chips agent-chips">
@for (option of prompts.items; track $index) {
<button type="button" class="ob-chip" (click)="prompt.emit(option.text)">
@if (option.icon) {
<mat-icon aria-hidden="true">{{ option.icon }}</mat-icon>
}
{{ option.text }}
</button>
}
</div>
}
@if (msg.chips?.length) {
<tb-ai-card-actions class="agent-chips" [actions]="chipActions(msg.chips)" (act)="chip.emit($event)"></tb-ai-card-actions>
}
@if (reportingIndex === $index) {
<div class="k-report" role="group" [attr.aria-label]="'ai-assistant.feedback.report' | translate">
<div class="k-report-t">{{ 'ai-assistant.feedback.what-went-wrong' | translate }}</div>
<div class="k-chips">
@for (problem of problems; track problem) {
<button type="button" class="ob-chip" [attr.aria-pressed]="reportProblem === problem" (click)="reportProblem = problem">
{{ 'ai-assistant.feedback.problem.' + problem | translate }}
</button>
}
</div>
<input #reportComment class="k-deny-in" type="text" maxlength="2000" spellcheck="false"
[placeholder]="'ai-assistant.feedback.comment' | translate" [attr.aria-label]="'ai-assistant.feedback.comment' | translate"
(keydown.enter)="$event.preventDefault(); sendReport($index, reportComment.value)"
(keydown.escape)="$event.stopPropagation(); closeReport()">
<p class="k-report-note">{{ 'ai-assistant.feedback.sent-with' | translate }}</p>
<div class="k-actions">
<button mat-flat-button type="button" [disabled]="!reportProblem" (click)="sendReport($index, reportComment.value)">
<mat-icon>send</mat-icon>{{ 'ai-assistant.feedback.send' | translate }}
</button>
<button mat-button type="button" (click)="closeReport()">{{ 'action.cancel' | translate }}</button>
</div>
</div>
}
}
</div>
@if (msg.from === 'APPROVAL' && denyReasonOf(msg); as reason) {
<div class="user">
<div class="msg">{{ reason }}</div>
</div>
}
}
}
@if (loading && !waitApproval) {
<div class="generating flex items-center gap-4">
@if (loadingLongTime) {
<ng-content select="[loadingLongTime]"></ng-content>
@if (loading && !waitApproval && !actionRunning && !streaming) {
<div class="generating flex items-center">
@if (work) {
<tb-ai-work-line class="work" [words]="work.headline || ('ai-assistant.work.' + work.moment | translate)" [since]="work.since"></tb-ai-work-line>
} @else {
<svg class="image-main-color w-6" preserveAspectRatio="xMidYMid meet" viewBox="0 0 42 48">
<use [attr.xlink:href]="'/assets/solution-creator/iot-assistant.svg#iot-assistant'"></use>
</svg>
<tb-ai-mark></tb-ai-mark>
<div class="glow-container">
{{ 'ai-assistant.thinking' | translate }}
</div>

620
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;
}

993
ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts

File diff suppressed because it is too large

56
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<boolean>;
atEnd: WritableSignal<boolean>;
newTurns: WritableSignal<number>;
}
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<AnswerRating, 'NONE'>; reported?: boolean}) => void;
send: (feedback: Omit<AnswerFeedback, 'answer'>) => Observable<void>;
failed: () => void;
}
export function aiRateAnswer(event: AnswerRatingEvent, before: Exclude<AnswerRating, 'NONE'> | 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();
}
});
}

49
ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html

@ -0,0 +1,49 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
@if (title(); as name) {
@if (renaming()) {
<span class="ai-chat-renaming">
<input #titleInput class="ai-chat-rename" [class.compact]="compact()" [value]="name"
[attr.aria-label]="'ai-assistant.chat-title' | translate"
(keydown)="onRenameKeydown($event)" (blur)="finishRename(titleInput.value)">
<button type="button" class="ai-ib" [attr.aria-label]="'ai-assistant.rename-save' | translate"
[matTooltip]="'ai-assistant.rename-save' | translate" matTooltipPosition="above"
(mousedown)="$event.preventDefault()" (click)="finishRename(titleInput.value)">
<mat-icon>check</mat-icon>
</button>
<button type="button" class="ai-ib" [attr.aria-label]="'ai-assistant.rename-discard' | translate"
[matTooltip]="'ai-assistant.rename-discard' | translate" matTooltipPosition="above"
(mousedown)="$event.preventDefault()" (click)="cancelRename()">
<mat-icon>close</mat-icon>
</button>
</span>
} @else {
<span class="ai-chat-name-wrap" [class.static]="!renamable()">
<button #chatName type="button" class="ai-chat-name" [class.clipped]="nameClipped()" [class.compact]="compact()"
[matTooltip]="nameClipped() ? name : renamable() ? ('ai-assistant.double-click-to-rename' | translate) : ''"
[matTooltipDisabled]="!nameClipped() && !renamable()"
matTooltipPosition="after" matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500"
(mouseenter)="nameClipped.set(chatName.scrollWidth > chatName.clientWidth + 1)"
(keydown.enter)="startRename()" (keydown.f2)="startRename()" (dblclick)="startRename()">{{ name }}</button>
@if (renamable()) {
<button type="button" class="ai-chat-name-pen" [attr.aria-label]="'action.rename' | translate"
[matTooltip]="'action.rename' | translate" matTooltipPosition="above" (click)="startRename()">
<mat-icon fontSet="material-icons-round">edit</mat-icon>
</button>
}
</span>
@if (level(); as current) {
<span class="ai-chat-status" [class]="'ai-chat-status ' + current"
[matTooltip]="statusTip()" [matTooltipDisabled]="!statusTip()" matTooltipPosition="below">
<span class="tb-ai-status-mark" [class]="'tb-ai-status-mark ' + current"></span>
<span>{{ ('ai-assistant.status-' + current) | translate }}</span>
</span>
}
}
} @else {
<span class="ai-chat-name" [class.compact]="compact()">{{ placeholder() }}</span>
}

144
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;
}

67
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<string | null | undefined>(null);
placeholder = input('');
level = input<ChatLevel | null>(null);
statusTip = input('');
renamable = input(true);
compact = input(false);
@Output() renamed = new EventEmitter<string>();
private host = inject<ElementRef<HTMLElement>>(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<HTMLInputElement>('.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);
}
}
}

480
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html

@ -0,0 +1,480 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="art-cols" [class.with-pane]="!!shownFile() && fileOpen()" [class.narrow]="docked()">
<div class="ai-chat-col">
<header class="ai-chat-head" [class.scrolled]="scrolled()" tb-fullscreen [fullscreenElement]="hostElement" [fullscreen]="fullscreen()"
(fullscreenChanged)="onFullscreenChanged($event)">
<ng-content select="[aiChatLead]"></ng-content>
@if (variant() === 'panel') {
<tb-ai-mark size="32"></tb-ai-mark>
}
<tb-ai-chat-title [title]="chat()?.title" [placeholder]="historyLoading() ? '' : ((showGetStarted() ? 'ai-assistant.get-started.title' : 'ai-assistant.new-chat') | translate)" [level]="level()"
[statusTip]="statusTip()" [compact]="variant() === 'panel'" (renamed)="rename($event)"></tb-ai-chat-title>
<div class="ai-chat-actions">
@if (chatFiles().length && !titleRef?.renaming()) {
<button type="button" class="ai-ib art-files-btn" [class.shown]="!!shownFile() && fileOpen()" [matMenuTriggerFor]="filesMenu"
(menuClosed)="unlisting.set(null)"
[matTooltip]="'ai-assistant.file.files' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length}">
<span class="art-files-ic" aria-hidden="true"><svg viewBox="0 0 24 24" focusable="false"><path d="M4 8.6A1.6 1.6 0 0 1 5.6 7h6.2l3.7 3.7v8.7a1.6 1.6 0 0 1-1.6 1.6H5.6A1.6 1.6 0 0 1 4 19.4Z"/><path d="M11.6 7v2.5a1.2 1.2 0 0 0 1.2 1.2h2.7"/><path d="M8.5 7V4.6A1.6 1.6 0 0 1 10.1 3h6.2L20 6.7v8.7a1.6 1.6 0 0 1-1.6 1.6h-2.9"/></svg></span>
<span class="art-files-n">{{ chatFiles().length }}</span>
</button>
}
@if (variant() === 'panel') {
@if (!titleRef?.renaming()) {
<button type="button" class="ai-ib more" [matMenuTriggerFor]="panelMenu"
[matTooltip]="'ai-assistant.chats-menu' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.chats-menu' | translate">
<mat-icon>more_vert</mat-icon>
</button>
<button type="button" class="ai-ib" (click)="toggleFullscreen()"
[matTooltip]="(fullscreen() ? 'fullscreen.exit' : 'ai-assistant.open-full-screen') | translate" matTooltipPosition="above"
[attr.aria-label]="(fullscreen() ? 'fullscreen.exit' : 'ai-assistant.open-full-screen') | translate">
<mat-icon fontSet="material-icons-round">{{ fullscreen() ? 'fullscreen_exit' : 'fullscreen' }}</mat-icon>
</button>
@if (!fullscreen()) {
<button type="button" class="ai-ib" (click)="closed.emit()"
[matTooltip]="'action.close' | translate" matTooltipPosition="above" [attr.aria-label]="'action.close' | translate">
<mat-icon fontSet="material-icons-round">close</mat-icon>
</button>
}
}
} @else if (chat() && !titleRef?.renaming()) {
<button type="button" class="ai-ib more" [matMenuTriggerFor]="chatMenu"
[matTooltip]="'action.more' | translate" matTooltipPosition="above" [attr.aria-label]="'action.more' | translate">
<mat-icon>more_vert</mat-icon>
</button>
}
<ng-content select="[aiChatActions]"></ng-content>
@if (showGetStarted()) {
<button type="button" class="ai-tour-link" (click)="takeTour.emit()">
<mat-icon fontSet="material-icons-round" aria-hidden="true">tour</mat-icon>
<span>{{ 'ai-assistant.get-started.take-tour' | translate }}</span>
</button>
}
@if (fullscreenEnabled()) {
<button type="button" class="ai-ib" (click)="toggleFullscreen()"
[matTooltip]="(fullscreen() ? 'fullscreen.exit' : 'fullscreen.expand') | translate" matTooltipPosition="above"
[attr.aria-label]="(fullscreen() ? 'fullscreen.exit' : 'fullscreen.expand') | translate">
<mat-icon fontSet="material-icons-round">{{ fullscreen() ? 'fullscreen_exit' : 'fullscreen' }}</mat-icon>
</button>
}
</div>
</header>
<div tb-toast [toastTarget]="toastTarget()" class="pointer-events-none absolute inset-0"></div>
<div #chatArea class="ai-chat-body" [class.empty]="!messages().length && !loading() && !historyLoading()" (scroll)="onLogScroll(chatArea)">
@if (messages().length || loading()) {
<tb-ai-chat-messages
class="ai-chat-log"
[messages]="messages()"
[loading]="loading()"
[completedExecutions]="completedExecutions()"
[autoApprove]="autoApprove()"
[additionalStyles]="markdownStyles"
[scrollContainer]="chatArea"
initialScroll="bottom"
[denyReasons]="denyReasons()"
[work]="work()"
(approvalAction)="onApprovalAction($event)"
(askAgain)="onAskAgain()"
[feedback]="!!chatId()"
(rate)="onRate($event)"
(report)="onReport($event)"
(resume)="resume()"
(autoApproveRest)="setAutoApprove(true)"
(runPlan)="runPlan($event)"
(changePlan)="changePlan()"
[shownFile]="fileOpen() ? (shownFile()?.executionId ?? null) : null"
[ghostFirst]="true"
(openFile)="showFile($event)"
(prompt)="ask($event)"
(stopRun)="stop()"
(compose)="composeText($event)"
(answer)="ask($event.message, $event.secrets)"
(editMessage)="promptInput?.setValue($event)">
</tb-ai-chat-messages>
} @else if (historyLoading()) {
<div class="ai-chat-loading" role="status">
<tb-ai-spin kind="think"></tb-ai-spin>
<span>{{ 'ai-assistant.loading-chat' | translate }}</span>
</div>
} @else if (!chatId() && docked()) {
<div class="k-newchat">
<tb-ai-mark size="44"></tb-ai-mark>
<h3>{{ startTitle() || ('ai-assistant.panel-title' | translate) }}</h3>
<p>{{ startLine() || ('ai-assistant.panel-line' | translate) }}</p>
@if (prompts().length) {
<div class="prompts" role="list">
@for (example of prompts(); track example.message) {
<button type="button" class="prompt" role="listitem" (click)="ask(example.message)">
<mat-icon fontSet="material-icons-round" aria-hidden="true">chat_bubble_outline</mat-icon>
<span>{{ example.label }}</span>
<mat-icon fontSet="material-icons-round" class="go" aria-hidden="true">arrow_upward</mat-icon>
</button>
}
</div>
}
</div>
} @else if (!chatId()) {
<div class="ai-chat-start">
<tb-ai-mark size="64"></tb-ai-mark>
@if (variant() === 'panel') {
<h1 class="ai-chat-start-title">{{ startTitle() || ('ai-assistant.panel-title' | translate) }}</h1>
<p class="ai-chat-start-line">{{ startLine() || ('ai-assistant.panel-line' | translate) }}</p>
} @else {
<h1 class="ai-chat-start-title">{{ (showGetStarted() ? 'ai-assistant.get-started.heading' : 'ai-assistant.what-to-work-on') | translate }}</h1>
}
</div>
}
<div #composer class="ai-chat-composer">
@if (pill(); as current) {
<button type="button" class="k-pill" [class.new]="current.mode === 'new'"
[matTooltip]="current.label" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.go-to-end' | translate"
(click)="goToEnd(chatArea)">
@if (current.mode === 'new') {
<mat-icon class="tb-mat-18">arrow_downward</mat-icon>{{ current.count }}
} @else {
<tb-ai-spin [kind]="current.kind"></tb-ai-spin>
}
</button>
}
@if (creditsOut(); as limitType) {
<tb-ai-credits-out [limitType]="limitType" (dismissed)="creditsOut.set(null)"></tb-ai-credits-out>
} @else if (limitOut(); as platformLimit) {
<tb-ai-limit-out [platformLimit]="platformLimit" (dismissed)="limitOut.set(null)"></tb-ai-limit-out>
} @else if (notice(); as current) {
<div class="k-notice k-notice-edge" [class]="'k-notice k-notice-edge ' + (current.kind === 'block' ? 'blocking' : current.kind)" [attr.role]="current.kind === 'block' ? 'alert' : 'status'">
<mat-icon aria-hidden="true">{{ current.icon }}</mat-icon><span>{{ current.text }}</span>
</div>
}
<tb-ai-prompt-input
[blocked]="notice()?.kind === 'block' || !!creditsOut()"
[docked]="docked()"
[placeholder]="placeholder()"
[suggestion]="suggestion()"
[quote]="composerQuote()"
(quoteRemoved)="composerQuote.set(null)"
[loading]="loading() && !waitingApproval()"
[dropZone]="chatArea"
[pinned]="!!messages().length || loading() || historyLoading()"
[showAutoApprove]="true"
[sendWhileWorking]="true"
[autoApprove]="autoApprove()"
[autoApproveInChat]="!!chatId()"
[stoppable]="!!chatId()"
[stopping]="stopping()"
(stopped)="stop()"
(autoApproveChange)="setAutoApprove($event)"
(messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input>
</div>
@if (variant() === 'panel' && !docked() && !chatId() && !messages().length && !loading() && prompts().length) {
<section class="ai-sec k-prompts" [attr.aria-label]="'ai-assistant.start-a-task' | translate">
<div class="prompts" role="list">
@for (example of prompts(); track example.message) {
<button type="button" class="prompt" role="listitem" (click)="ask(example.message)">
<mat-icon fontSet="material-icons-round" aria-hidden="true">chat_bubble_outline</mat-icon>
<span>{{ example.label }}</span>
<mat-icon fontSet="material-icons-round" class="go" aria-hidden="true">arrow_upward</mat-icon>
</button>
}
</div>
</section>
}
@if (showGetStarted() && !messages().length && !loading()) {
<section class="ai-sec ai-sec-lg" aria-labelledby="ai-sec-examples">
<div class="ai-sec-head">
<h2 id="ai-sec-examples">{{ 'ai-assistant.get-started.examples' | translate }}</h2>
<p>{{ 'ai-assistant.get-started.examples-hint' | translate }}</p>
</div>
<div class="k-pcards">
@for (example of examples; track example.key) {
<button type="button" class="k-pcard" (click)="startExample(example)">
<span class="k-pcard-tile"><mat-icon fontSet="material-icons-round" aria-hidden="true">{{ example.icon }}</mat-icon></span>
<span class="k-pcard-body">
<b>{{ ('ai-assistant.get-started.example.' + example.key + '.title') | translate }}</b>
<span>{{ ('ai-assistant.get-started.example.' + example.key + '.what') | translate }}</span>
</span>
</button>
}
</div>
</section>
<section class="ai-cli-band" aria-labelledby="ai-cli-band-h">
<span class="ai-cli-band-tile" aria-hidden="true"><mat-icon fontSet="material-icons-round">terminal</mat-icon></span>
<div class="ai-cli-band-text">
<h2 id="ai-cli-band-h">{{ 'ai-assistant.cli.band.heading' | translate }}</h2>
<p>{{ 'ai-assistant.cli.band.line' | translate }}</p>
</div>
<button type="button" class="ai-cli-band-btn" (click)="openCli.emit()">
<span>{{ 'ai-assistant.cli.band.action' | translate }}</span>
<mat-icon fontSet="material-icons-round" aria-hidden="true">arrow_forward</mat-icon>
</button>
</section>
}
@if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) {
<section class="ai-sec" aria-labelledby="ai-sec-tasks">
<div class="ai-sec-head"><h2 id="ai-sec-tasks">{{ 'ai-assistant.start-a-task' | translate }}</h2></div>
<div class="ai-tasks">
@for (task of tasks; track task) {
<button type="button" class="ai-task" (click)="startTask(task)">
<b>{{ ('ai-assistant.task.' + task + '.title') | translate }}</b>
<small>{{ ('ai-assistant.task.' + task + '.hint') | translate }}</small>
<mat-icon fontSet="material-icons-round" aria-hidden="true">chevron_right</mat-icon>
</button>
}
</div>
</section>
}
@if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) {
<button type="button" class="ai-sol-card" (click)="newSolution.emit()">
<tb-ai-mark class="ai-sol-card-mark" size="44" icon="layers"></tb-ai-mark>
<span class="ai-sol-card-text">
<b>{{ 'ai-assistant.create-solution' | translate }}</b>
<small>{{ 'ai-assistant.create-solution-hint' | translate }}</small>
</span>
<span class="ai-sol-card-go">
<span class="ai-sol-card-go-t">{{ 'ai-assistant.create-solution-start' | translate }}</span>
<mat-icon fontSet="material-icons-round" aria-hidden="true">arrow_forward</mat-icon>
</span>
</button>
}
</div>
</div>
@if (shownFile(); as file) {
@if (fileOpen()) {
<tb-ai-artifact-pane [class.art-dark]="fileDark(file)" [dark]="fileCode(file)" (closed)="fileOpen.set(false)">
<h2 artHead class="art-title" [matTooltip]="file.name" matTooltipPosition="below" [matTooltipShowDelay]="600">
<mat-icon class="tb-mat-20" aria-hidden="true">{{ fileMark(file) }}</mat-icon>
<span class="art-name">{{ fileName(file.name).base }}<span class="art-ext">{{ fileName(file.name).ext }}</span></span>
</h2>
<div artHead class="art-head-r">
@if (!file.previewed) {
<div class="art-tools">
@if (!fileBody()?.editing()) {
<button type="button" class="art-tool icon-only" (click)="fileBody()?.openFind()"
[matTooltip]="'ai-assistant.file.find' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.find' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">search</mat-icon>
</button>
}
<button type="button" class="art-tool icon-only" [class.on]="fileWrap()" [attr.aria-pressed]="fileWrap()" (click)="toggleFileWrap()"
[matTooltip]="'ai-assistant.file.wrap' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.wrap' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">wrap_text</mat-icon>
</button>
<button type="button" class="art-tool icon-only" [matMenuTriggerFor]="fileOptions"
[matTooltip]="'ai-assistant.file.more' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.more' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">more_vert</mat-icon>
</button>
</div>
}
<div class="art-tools">
<button type="button" class="art-tool icon-only art-copy" [class.copied]="fileCopied()" (click)="copyFile(file)"
[matTooltip]="(fileCopied() ? 'ai-assistant.copied' : 'ai-assistant.file.copy') | translate" matTooltipPosition="below"
[attr.aria-label]="'ai-assistant.file.copy' | translate">
<mat-icon class="tb-mat-18 art-copy-ic" aria-hidden="true">content_copy</mat-icon>
<svg class="art-copy-ok" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12.5l4.2 4.2L19 7"/></svg>
</button>
<span class="tb-ai-sr-only" aria-live="polite">{{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }}</span>
@if (file.image) {
<button type="button" class="art-tool icon-only" [matMenuTriggerFor]="imageDownloads"
[matTooltip]="'ai-assistant.file.download' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.download' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">download</mat-icon>
</button>
} @else {
<button type="button" class="art-tool icon-only" (click)="downloadFile(file)"
[matTooltip]="'ai-assistant.file.download' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.download' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">download</mat-icon>
</button>
}
</div>
</div>
<tb-ai-file-body [file]="file" [wrap]="fileWrap()" [whitespace]="fileWhitespace()" [saver]="fileSaver"
[marks]="fileMarks()" (marksChange)="fileMarks.set($event)" (discarded)="onFileDiscarded($event)"></tb-ai-file-body>
<ng-container ngProjectAs="[artFoot]">
@if (fileMarks(); as marks) {
<footer artFoot class="art-pane-foot art-marks">
<span class="file-marked">
<span class="file-marked-n">{{ (marks.from === marks.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: marks.from, to: marks.to} }}</span>
{{ 'ai-assistant.file.marked' | translate }}
</span>
<span class="art-spacer"></span>
<button mat-button type="button" (click)="fileMarks.set(null)">{{ 'ai-assistant.file.clear' | translate }}</button>
<button mat-stroked-button type="button" (click)="copyMarked(file)"><mat-icon>content_copy</mat-icon>{{ 'action.copy' | translate }}</button>
<button mat-flat-button type="button" class="art-ask" (click)="askAboutMarks(file)"><mat-icon>auto_awesome</mat-icon>{{ 'ai-assistant.file.ask-about' | translate }}</button>
</footer>
} @else {
<footer artFoot class="art-pane-foot file-bar">
<span class="file-bar-info">
@if (fileBody()?.editing()) {
@if (fileBody()?.dirty()) {
<span class="file-bar-state"><i class="file-bar-dot" aria-hidden="true"></i>{{ 'ai-assistant.file.unsaved' | translate }}</span>
} @else {
<span class="file-bar-state">{{ 'ai-assistant.file.editing' | translate }}</span>
}
@if (fileBody()?.caret(); as caret) {
<i class="file-bar-sep" aria-hidden="true">·</i>
<span class="file-bar-pos">{{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }}@if (caret.selected) { ({{ 'ai-assistant.file.selected' | translate: {count: caret.selected} }})}</span>
}
} @else if (fileBody()?.saved()) {
<span class="file-bar-saved"><mat-icon aria-hidden="true">check</mat-icon>{{ 'ai-assistant.file.saved' | translate }}</span>
} @else {
<span>{{ 'ai-assistant.file.lines' | translate: {count: file.lines} }}</span>
<i class="file-bar-sep" aria-hidden="true">·</i>
<span>{{ file.size }}</span>
@if (file.edited) {
<i class="file-bar-sep" aria-hidden="true">·</i>
<span class="file-bar-ed">{{ 'ai-assistant.file.edited-in-chat' | translate }}</span>
}
}
</span>
<span class="file-bar-acts">
@if (fileBody()?.editing()) {
@if (fileBody()?.dirty()) {
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.discard()">{{ 'ai-assistant.file.discard' | translate }}</button>
<button mat-flat-button type="button" class="file-bar-b file-bar-save" [disabled]="loading() || fileBody()?.saving()" (click)="fileBody()?.save()">
{{ 'ai-assistant.file.save' | translate }}
</button>
} @else {
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.done()">{{ 'ai-assistant.file.done' | translate }}</button>
}
} @else if (chatId()) {
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.startEdit()">
<mat-icon>edit</mat-icon>{{ 'ai-assistant.file.edit' | translate }}
</button>
}
</span>
</footer>
}
</ng-container>
</tb-ai-artifact-pane>
<mat-menu #imageDownloads="matMenu" xPosition="before" class="tb-ai-chat-menu">
<button mat-menu-item type="button" (click)="downloadFile(file)">
<mat-icon fontSet="material-icons-round">image</mat-icon><span>{{ 'ai-assistant.file.download-svg' | translate }}</span>
</button>
<button mat-menu-item type="button" (click)="downloadFileAsPng(file)">
<mat-icon fontSet="material-icons-round">photo</mat-icon><span>{{ 'ai-assistant.file.download-png' | translate }}</span>
</button>
</mat-menu>
<mat-menu #fileOptions="matMenu" xPosition="before" class="tb-ai-chat-menu art-opts">
@if (!fileBody()?.editing()) {
<button mat-menu-item role="menuitemcheckbox" [attr.aria-checked]="fileWhitespace()" (click)="$event.stopPropagation(); toggleFileWhitespace()">
<mat-icon fontSet="material-icons-round">space_bar</mat-icon>
<span class="art-opt-l">{{ 'ai-assistant.file.show-whitespace' | translate }}</span>
<span class="art-switch" [class.on]="fileWhitespace()" aria-hidden="true"><i></i></span>
</button>
}
<div class="art-opt-row" role="group" [attr.aria-label]="'ai-assistant.file.theme' | translate" (click)="$event.stopPropagation()">
<mat-icon fontSet="material-icons-round" aria-hidden="true">contrast</mat-icon>
<span>{{ 'ai-assistant.file.theme' | translate }}</span>
<div class="art-modes art-opt-modes" role="radiogroup">
<button type="button" role="radio" [attr.aria-checked]="fileTheme() === 'dark'" (click)="setFileTheme('dark')">
<mat-icon class="tb-mat-16" aria-hidden="true">dark_mode</mat-icon><span>{{ 'ai-assistant.file.dark' | translate }}</span>
</button>
<button type="button" role="radio" [attr.aria-checked]="fileTheme() === 'light'" (click)="setFileTheme('light')">
<mat-icon class="tb-mat-16" aria-hidden="true">light_mode</mat-icon><span>{{ 'ai-assistant.file.light' | translate }}</span>
</button>
</div>
</div>
</mat-menu>
}
}
</div>
<mat-menu #panelMenu="matMenu" xPosition="before" class="tb-ai-chat-menu">
@if (chat()) {
<button mat-menu-item (click)="startRename()">
<mat-icon fontSet="material-icons-round">edit</mat-icon>
<span>{{ 'action.rename' | translate }}</span>
</button>
<button mat-menu-item (click)="newChat()">
<mat-icon fontSet="material-icons-round">add</mat-icon>
<span>{{ 'ai-assistant.new-chat' | translate }}</span>
</button>
}
@if (docked() && (split() || splitAvailable())) {
<button mat-menu-item (click)="splitToggle.emit()">
<mat-icon fontSet="material-icons-round">{{ split() ? 'view_sidebar' : 'vertical_split' }}</mat-icon>
<span>{{ (split() ? 'ai-assistant.back-to-panel' : 'ai-assistant.split-view') | translate }}</span>
</button>
}
@if (recentChats().length) {
<div class="tb-ai-menu-h">{{ 'ai-assistant.recent-chats' | translate }}</div>
@for (other of recentChats(); track other.id) {
<button mat-menu-item class="chat" (click)="chatId.set(other.id)">
<mat-icon fontSet="material-icons-round">chat_bubble_outline</mat-icon>
<span class="tb-ai-menu-chat">
<span class="t">{{ other.title }}</span>
@if (levelOf(other); as level) {
<span class="tb-ai-status-mark" [class]="'tb-ai-status-mark ' + level"></span>
}
</span>
</button>
}
}
<button mat-menu-item (click)="openAllChats()">
<mat-icon fontSet="material-icons-round">forum</mat-icon>
<span>{{ 'ai-assistant.all-chats' | translate }}</span>
</button>
@if (chat()) {
<button mat-menu-item class="danger" (click)="deleteChat()">
<mat-icon fontSet="material-icons-round">delete_outline</mat-icon>
<span>{{ 'action.delete' | translate }}</span>
</button>
}
</mat-menu>
<mat-menu #chatMenu="matMenu" xPosition="before" class="tb-ai-chat-menu">
<button mat-menu-item (click)="startRename()">
<mat-icon fontSet="material-icons-round">edit</mat-icon>
<span>{{ 'action.rename' | translate }}</span>
</button>
<button mat-menu-item (click)="togglePinned()">
<mat-icon fontSet="material-icons-round">push_pin</mat-icon>
<span>{{ (chat()?.pinned ? 'ai-assistant.unpin' : 'ai-assistant.pin') | translate }}</span>
</button>
<button mat-menu-item class="danger" (click)="deleteChat()">
<mat-icon fontSet="material-icons-round">delete_outline</mat-icon>
<span>{{ 'action.delete' | translate }}</span>
</button>
</mat-menu>
<mat-menu #filesMenu="matMenu" xPosition="before" class="tb-ai-chat-menu art-list">
<div class="tb-ai-menu-h art-list-h">{{ 'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length} }}</div>
@for (entry of chatFiles(); track entry.file.name) {
@if (unlisting() === entry.file.name) {
<div class="art-list-confirm" (click)="$event.stopPropagation()" (keydown.escape)="keepListed($event)">
<span class="art-list-ic"><mat-icon class="tb-mat-18" aria-hidden="true">{{ fileMark(entry.file) }}</mat-icon></span>
<span class="art-list-q"><b>{{ 'ai-assistant.file.unlist-ask' | translate }}</b>
<small><span class="art-name">{{ fileName(entry.file.name).base }}<span class="art-ext">{{ fileName(entry.file.name).ext }}</span></span></small></span>
<button type="button" class="art-list-no" (click)="keepListed($event)"
[matTooltip]="'ai-assistant.file.keep' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.keep' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">close</mat-icon>
</button>
<button type="button" class="art-list-yes" (click)="unlist(entry.file, $event)"
[matTooltip]="'ai-assistant.file.unlist-do' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.unlist-do' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">delete_outline</mat-icon>
</button>
</div>
} @else {
<div class="art-list-row">
<button mat-menu-item type="button" class="art-list-item" [class.on]="isShownFile(entry.file)" role="menuitemradio"
[attr.aria-checked]="isShownFile(entry.file)" (click)="showFile(entry.file)" (keydown.delete)="askUnlist(entry.file, $event)">
<span class="art-list-ic"><mat-icon class="tb-mat-18" aria-hidden="true">{{ fileMark(entry.file) }}</mat-icon></span>
<span class="art-list-t"><b><span class="art-name">{{ fileName(entry.file.name).base }}<span class="art-ext">{{ fileName(entry.file.name).ext }}</span></span></b></span>
@if (entry.running) {
<tb-ai-spin kind="gen"></tb-ai-spin>
}
@if (isShownFile(entry.file)) {
<mat-icon class="tb-mat-18 art-list-check" aria-hidden="true">check</mat-icon>
}
</button>
<button type="button" class="art-list-del" tabindex="-1" (click)="askUnlist(entry.file, $event)"
[matTooltip]="'ai-assistant.file.unlist' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.unlist' | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">delete_outline</mat-icon>
</button>
</div>
}
}
</mat-menu>

792
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;
}
}

1524
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts

File diff suppressed because it is too large

938
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<string, CodeLanguage> = {
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<string, CodeLanguage> = {
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<string, string> = {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<string, string> = {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<Element>();
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<GroupPick>) => {
document.querySelectorAll<PickableBlock>('[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<GroupPick>(GROUP_EVENT, {detail: {group, id, from}}));
}
export function onCodeTabGroup(group: string, picked: (id: string) => void): () => void {
const listener = (event: CustomEvent<GroupPick>) => {
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<typeof setTimeout>;
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<string, RegExp> = {
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('<!--')) {
const [pieces, rest] = blockComment(line, state, '<!--', '-->');
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 = /(?<tag><\/?[\w:-]+)|(?<close>\/?>)|(?<attr>[\w:@.[\]()*#-]+)(?==)|(?<eq>=)|(?<str>"[^"]*"?|'[^']*'?)|(?<bind>\{\{.*?\}\})|(?<flow>@(?:if|else if|else|for|empty|switch|case|default|let)\b)|(?<other>[^<>="'{@]+|[{@>])/g;
for (const match of text.matchAll(pattern)) {
const groups = match.groups ?? {};
if (groups.tag) {
out.push(token('op', groups.tag.startsWith('</') ? '</' : '<'), token('kw', groups.tag.replace(/^<\/?/, '')));
} else if (groups.close || groups.eq) {
out.push(token('op', match[0]));
} else if (groups.attr) {
out.push(token('key', groups.attr));
} else if (groups.str) {
out.push(token('str', groups.str));
} else if (groups.bind) {
out.push(token('var', groups.bind));
} else if (groups.flow) {
out.push(token('kw', groups.flow));
} else {
out.push(match[0]);
}
}
return out;
}
function cssLine(line: string, state: ShellState): Piece[] {
const [pieces, rest] = state.comment || line.includes('/*') ? blockComment(line, state, '/*', '*/') : [[], line];
return [...pieces.flatMap(piece => 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);
});
}

33
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 {}

44
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 {}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save