Browse Source

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

Sanitized HTML in AI Assistant content, applied the AI chat requests rate limit and sorted alarms by severity priority
pull/16888/head
Vladyslav Prykhodko 22 hours ago
committed by GitHub
parent
commit
ddbb35a73e
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 3
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 3
      application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java
  3. 1
      application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
  4. 6
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  5. 12
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  6. 6
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  7. 12
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
  8. 4
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  9. 38
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
  10. 11
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
  11. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
  12. 15
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  13. 17
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
  14. 11
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
  15. 16
      application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
  16. 30
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  17. 25
      application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
  18. 6
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
  19. 81
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java
  20. 7
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java
  21. 23
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java
  22. 28
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
  23. 3
      common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java
  24. 2
      common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java
  25. 29
      common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java
  26. 4
      common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java
  27. 75
      common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java
  28. 33
      dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java
  29. 6
      dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java
  30. 21
      dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java
  31. 1
      ui-ngx/package.json
  32. 36
      ui-ngx/src/app/core/http/user-permissions.service.ts
  33. 32
      ui-ngx/src/app/core/interceptors/global-http-interceptor.ts
  34. 1
      ui-ngx/src/app/core/notification/notification.models.ts
  35. 25
      ui-ngx/src/app/core/services/ai-assistant-panel.service.ts
  36. 13
      ui-ngx/src/app/core/services/ai-solutions.service.ts
  37. 2
      ui-ngx/src/app/core/services/menu.models.ts
  38. 2
      ui-ngx/src/app/core/services/tour.service.ts
  39. 16
      ui-ngx/src/app/core/utils.ts
  40. 7
      ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss
  41. 2
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html
  42. 23
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html
  43. 17
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts
  44. 73
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  45. 5
      ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts
  46. 2
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  47. 3
      ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss
  48. 33
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  49. 8
      ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts
  50. 2
      ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts
  51. 12
      ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html
  52. 2
      ui-ngx/src/app/modules/home/components/ai/ai-text.ts
  53. 44
      ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts
  54. 5
      ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts
  55. 2
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html
  56. 15
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts
  57. 3
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html
  58. 7
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts
  59. 2
      ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html
  60. 23
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts
  61. 4
      ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts
  62. 4
      ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts
  63. 2
      ui-ngx/src/app/modules/home/home.component.html
  64. 16
      ui-ngx/src/app/modules/home/home.component.ts
  65. 6
      ui-ngx/src/app/modules/home/menu/menu-link.component.ts
  66. 14
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts
  67. 64
      ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts
  68. 4
      ui-ngx/src/app/modules/home/pages/home-page/home-permissions.service.ts
  69. 24
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts
  70. 172
      ui-ngx/src/app/shared/components/markdown-html-sanitize.ts
  71. 12
      ui-ngx/src/app/shared/components/markdown.component.ts
  72. 2
      ui-ngx/src/app/shared/components/toast.directive.ts
  73. 1
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  74. 11
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  75. 45
      ui-ngx/src/theme/ai-theme.scss

3
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -31,7 +31,6 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.device.DeviceConnectivityHostSource; import org.thingsboard.server.dao.device.DeviceConnectivityHostSource;
import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.device.DeviceConnectivityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
@ -224,7 +223,7 @@ public class IotHubController extends BaseController {
} }
private void checkAllPermissions() throws ThingsboardException { private void checkAllPermissions() throws ThingsboardException {
if (!getCurrentUser().getUserPermissions().hasGenericPermission(Resource.ALL, Operation.ALL)) { if (!getCurrentUser().getUserPermissions().hasGenericPermissionExceptAi(Operation.ALL)) {
throw new ThingsboardException("You don't have permissions to use solution templates!", throw new ThingsboardException("You don't have permissions to use solution templates!",
ThingsboardErrorCode.PERMISSION_DENIED); ThingsboardErrorCode.PERMISSION_DENIED);
} }

3
application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java

@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.UsageInfo; import org.thingsboard.server.common.data.UsageInfo;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.usage.UsageInfoService; import org.thingsboard.server.dao.usage.UsageInfoService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -30,7 +29,7 @@ public class UsageInfoController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping(value = "/usage") @GetMapping(value = "/usage")
public UsageInfo getTenantUsageInfo() throws ThingsboardException { public UsageInfo getTenantUsageInfo() throws ThingsboardException {
if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermission(Resource.ALL, Operation.READ)) { if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermissionExceptAi(Operation.READ)) {
throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED); throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED);
} }
return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId())); return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId()));

1
application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java

@ -93,6 +93,7 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand
errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN); errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN);
errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT); errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT);
errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED); errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED);
errorCodeToStatusMap.put(ThingsboardErrorCode.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE);
} }
private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) { private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) {

6
application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java

@ -153,9 +153,9 @@ class DefaultTbAiService implements TbAiService {
private static String toUserFriendlyMessage(Throwable e) { private static String toUserFriendlyMessage(Throwable e) {
if (e instanceof TimeoutException) { if (e instanceof TimeoutException) {
return "Request timed out"; return TbAiOperations.TIMED_OUT_MESSAGE;
} else if (e instanceof TbAiChannelUnavailableException) { } else if (e instanceof TbAiChannelUnavailableException) {
return "Service unavailable"; return TbAiOperations.UNAVAILABLE_MESSAGE;
} else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) { } else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) {
return e.getMessage(); return e.getMessage();
} }
@ -177,6 +177,8 @@ class DefaultTbAiService implements TbAiService {
case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND; case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND;
case 409 -> ThingsboardErrorCode.VERSION_CONFLICT; case 409 -> ThingsboardErrorCode.VERSION_CONFLICT;
case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS; case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS;
case 401, 403 -> ThingsboardErrorCode.PERMISSION_DENIED;
case 502, 503, 504 -> ThingsboardErrorCode.SERVICE_UNAVAILABLE;
default -> ThingsboardErrorCode.GENERAL; default -> ThingsboardErrorCode.GENERAL;
}; };
} }

12
application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java

@ -9,6 +9,8 @@ import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperation;
@ -27,10 +29,12 @@ import java.util.UUID;
class DefaultAiChatService implements AiChatService { class DefaultAiChatService implements AiChatService {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true); private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
static final String RATE_LIMITED = "RATE_LIMITED";
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport; private final TbAiTransport tbAiTransport;
private final TbAiOperations operations; private final TbAiOperations operations;
private final RateLimitService rateLimitService;
@Override @Override
public JsonNode createChat(JsonNode request, SecurityUser user) { public JsonNode createChat(JsonNode request, SecurityUser user) {
@ -79,6 +83,14 @@ class DefaultAiChatService implements AiChatService {
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin, UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user SecurityUser user
) { ) {
if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
return Flux.just(ServerSentEvent.<String>builder()
.event("error")
.data(JacksonUtil.toString(JacksonUtil.newObjectNode()
.put("message", "Rate limit exceeded")
.put("code", RATE_LIMITED)))
.build());
}
var link = new TbAiTurnLink(); var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> { return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);

6
application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java

@ -10,6 +10,8 @@ import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.common.data.util.CollectionsUtil; import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest; import org.thingsboard.ai.common.channel.SolutionChatRequest;
@ -33,6 +35,7 @@ public class DefaultAiSolutionService implements AiSolutionService {
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiOperations operations; private final TbAiOperations operations;
private final RateLimitService rateLimitService;
@Override @Override
public JsonNode startNew(SecurityUser user) { public JsonNode startNew(SecurityUser user) {
@ -59,6 +62,9 @@ public class DefaultAiSolutionService implements AiSolutionService {
if (StringUtils.isBlank(text) && attached == null) { if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS); throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
} }
if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
throw new ThingsboardRuntimeException("Rate limit exceeded", ThingsboardErrorCode.TOO_MANY_REQUESTS);
}
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user); new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
} }

12
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java

@ -52,7 +52,7 @@ class ChannelTbAiOperations {
} catch (NotStartedException e) { } catch (NotStartedException e) {
if (attempt >= 2) { if (attempt >= 2) {
log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage()); log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage());
return failure("Service unavailable"); return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
} }
log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage()); log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage());
fresh = true; fresh = true;
@ -76,8 +76,8 @@ class ChannelTbAiOperations {
} }
} }
static TbAiResponse failure(String message) { static TbAiResponse failure(HttpStatus status, String message) {
return TbAiResponse.builder().success(false).error(message).build(); return TbAiResponse.builder().success(false).status(status.value()).error(message).build();
} }
static TbAiResponse toResponse(OperationResult result) { static TbAiResponse toResponse(OperationResult result) {
@ -136,15 +136,15 @@ class ChannelTbAiOperations {
return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
return failure("Request interrupted"); return failure(HttpStatus.SERVICE_UNAVAILABLE, "Request interrupted");
} catch (TimeoutException e) { } catch (TimeoutException e) {
return failure("Request timed out"); return failure(HttpStatus.GATEWAY_TIMEOUT, TbAiOperations.TIMED_OUT_MESSAGE);
} catch (ExecutionException e) { } catch (ExecutionException e) {
if (e.getCause() instanceof NotStartedException notStarted) { if (e.getCause() instanceof NotStartedException notStarted) {
throw notStarted; throw notStarted;
} }
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e)); log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e));
return failure("Service unavailable"); return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
} finally { } finally {
finish(); finish();
} }

4
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java

@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or * Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or
* closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails * closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails
* the turn with "Service unavailable". * the turn with {@link TbAiOperations#UNAVAILABLE_MESSAGE}.
*/ */
@Slf4j @Slf4j
@Component @Component
@ -166,7 +166,7 @@ class ChannelTbAiTransport implements TbAiTransport {
end(null); end(null);
} else { } else {
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason); log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason);
end(errorEvent("Service unavailable")); end(errorEvent(TbAiOperations.UNAVAILABLE_MESSAGE));
} }
} }

38
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java

@ -2,6 +2,8 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport; package org.thingsboard.server.service.ai.transport;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbAiChannelClient; import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.client.TbAiClaims;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.common.util.ThingsBoardThreadFactory;
@ -120,11 +123,17 @@ class TbAiChannelPool {
PoolKey key = new PoolKey(context.tenantId(), context.userId()); PoolKey key = new PoolKey(context.tenantId(), context.userId());
CompletableFuture<TbAiPooledConnection> pending = null; CompletableFuture<TbAiPooledConnection> pending = null;
if (!fresh) { if (!fresh) {
String limits = limitsOf(currentToken(context));
Group group = groups.computeIfAbsent(key, k -> new Group()); Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) { synchronized (group) {
long now = nanoClock.getAsLong(); long now = nanoClock.getAsLong();
for (int i = group.connections.size() - 1; i >= 0; i--) { for (int i = group.connections.size() - 1; i >= 0; i--) {
TbAiPooledConnection connection = group.connections.get(i); TbAiPooledConnection connection = group.connections.get(i);
if (connection.isStaleFor(limits)) {
log.debug("[{}] Retiring an AI channel opened with other limits", key);
connection.retire();
continue;
}
if (connection.tryReserve(now)) { if (connection.tryReserve(now)) {
return CompletableFuture.completedFuture(connection); return CompletableFuture.completedFuture(connection);
} }
@ -185,7 +194,9 @@ class TbAiChannelPool {
private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) { private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) {
var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled, var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled,
maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong()); maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong());
channelClient.connect(handshakeTokenProvider(context), connection) String token = currentToken(context);
connection.handshakeLimits(limitsOf(token));
channelClient.connect(handshakeTokenProvider(context, token), connection)
.subscribeOn(Schedulers.boundedElastic()) .subscribeOn(Schedulers.boundedElastic())
.subscribe(connection::opened, error -> connection.failed(toConnectError(error))); .subscribe(connection::opened, error -> connection.failed(toConnectError(error)));
return connection.ready() return connection.ready()
@ -298,13 +309,32 @@ class TbAiChannelPool {
return true; return true;
} }
private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) { private static String currentToken(TbAiTurnContext context) {
try {
return context.tokenProvider() != null ? context.tokenProvider().getToken() : null;
} catch (RuntimeException e) {
return null;
}
}
static String limitsOf(String token) {
if (token == null) {
return null;
}
try {
return JWT.decode(token).getClaim(TbAiClaims.PROFILE_CONFIG).asString();
} catch (JWTDecodeException e) {
return null;
}
}
private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context, String token) {
TbAiClient.TokenProvider delegate = context.tokenProvider(); TbAiClient.TokenProvider delegate = context.tokenProvider();
String acceptLanguage = context.acceptLanguage(); String acceptLanguage = context.acceptLanguage();
return new TbAiClient.TokenProvider() { return new TbAiClient.TokenProvider() {
@Override @Override
public String getToken() { public String getToken() {
return delegate.getToken(); return token != null ? token : delegate.getToken();
} }
@Override @Override
@ -324,7 +354,7 @@ class TbAiChannelPool {
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) { if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) {
int status = handshake.response().status().code(); int status = handshake.response().status().code();
if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) { if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) {
return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase()); return new TbAiChannelRejectedException(HttpStatus.valueOf(status));
} }
} }
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) { if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {

11
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java

@ -2,13 +2,20 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport; package org.thingsboard.server.service.ai.transport;
import lombok.Getter;
import org.springframework.http.HttpStatus;
/** /**
* TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user. * TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user.
*/ */
@Getter
public class TbAiChannelRejectedException extends RuntimeException { public class TbAiChannelRejectedException extends RuntimeException {
public TbAiChannelRejectedException(String reason) { private final HttpStatus status;
super(reason);
public TbAiChannelRejectedException(HttpStatus status) {
super(status.getReasonPhrase());
this.status = status;
} }
} }

8
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java

@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai.transport;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
@ -17,6 +18,9 @@ import org.thingsboard.server.service.security.system.SystemSecurityService;
@RequiredArgsConstructor @RequiredArgsConstructor
public class TbAiOperations { public class TbAiOperations {
public static final String UNAVAILABLE_MESSAGE = "The AI service is unavailable. Try again.";
public static final String TIMED_OUT_MESSAGE = "The AI service did not answer in time. Try again.";
private final ChannelTbAiOperations channelOperations; private final ChannelTbAiOperations channelOperations;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -33,9 +37,9 @@ public class TbAiOperations {
return channelOperations.execute(operation, context); return channelOperations.execute(operation, context);
} catch (TbAiChannelUnavailableException e) { } catch (TbAiChannelUnavailableException e) {
log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage()); log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage());
return ChannelTbAiOperations.failure("Service unavailable"); return ChannelTbAiOperations.failure(HttpStatus.SERVICE_UNAVAILABLE, UNAVAILABLE_MESSAGE);
} catch (TbAiChannelRejectedException e) { } catch (TbAiChannelRejectedException e) {
return ChannelTbAiOperations.failure(e.getMessage()); return ChannelTbAiOperations.failure(e.getStatus(), e.getMessage());
} }
} }

15
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java

@ -54,6 +54,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
private volatile ChannelSession session; private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
private volatile List<String> serverCapabilities = List.of(); private volatile List<String> serverCapabilities = List.of();
private volatile String handshakeLimits;
/** /**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot * Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
@ -198,6 +199,20 @@ final class TbAiPooledConnection implements ChannelFrameListener {
} }
} }
void handshakeLimits(String limits) {
this.handshakeLimits = limits;
}
/**
* True when the channel shook hands with other limits than the caller's current token carries (the tenant
* profile's rate limits among them): its view of the user is out of date, so it should take no new work. Claims
* that change on every signing, such as the client address or the issue time, do not count.
*/
boolean isStaleFor(String currentLimits) {
String limits = handshakeLimits;
return currentLimits != null && limits != null && !limits.equals(currentLimits);
}
void retire() { void retire() {
boolean close; boolean close;
synchronized (lock) { synchronized (lock) {

17
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java

@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.TextNode;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
@ -69,6 +71,8 @@ import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.exception.ThingsboardEntitiesLimitExceededResponse;
import org.thingsboard.server.exception.ThingsboardErrorResponse;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
@ -242,7 +246,7 @@ public class DefaultDevicePackageService extends AbstractTbEntityService impleme
applied = change.apply(); applied = change.apply();
} catch (StepFailure e) { } catch (StepFailure e) {
log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause());
return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey); return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey, limitOf(e.getCause()));
} catch (RestClientException e) { } catch (RestClientException e) {
log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e);
return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null);
@ -1068,6 +1072,17 @@ public class DefaultDevicePackageService extends AbstractTbEntityService impleme
* The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database
* error, as a common message, with the details in the log. * error, as a common message, with the details in the log.
*/ */
static JsonNode limitOf(Throwable e) {
SubscriptionException subscription = ExceptionUtils.throwableOfType(e, SubscriptionException.class);
if (subscription != null) {
return JacksonUtil.valueToTree(ThingsboardErrorResponse.ofSubscriptionViolation(subscription.getMessage(), subscription.getErrorCode(),
subscription.getEntry(), subscription.getValue(), HttpStatus.FORBIDDEN));
}
EntitiesLimitExceededException entities = ExceptionUtils.throwableOfType(e, EntitiesLimitExceededException.class);
return entities == null ? null
: JacksonUtil.valueToTree(ThingsboardEntitiesLimitExceededResponse.of(entities.getMessage(), entities.getEntityType(), entities.getLimit()));
}
static String userMessage(Throwable e) { static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) { if (e instanceof EntityVersionMismatchException) {
return "Someone changed it meanwhile. Check the package again."; return "Someone changed it meanwhile. Check the package again.";

11
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub; package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
@ -25,13 +26,19 @@ public class DevicePackageResult {
private DeviceInstalledItemDescriptor descriptor; private DeviceInstalledItemDescriptor descriptor;
// By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs; private Map<String, ObjectNode> outputs;
// When a step failed on an entity or subscription limit: the same body ThingsBoard answers such a request with (403)
private JsonNode limit;
public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DevicePackageResult(true, null, null, descriptor, outputs); return new DevicePackageResult(true, null, null, descriptor, outputs, null);
} }
public static DevicePackageResult error(String errorMessage, String failedStep) { public static DevicePackageResult error(String errorMessage, String failedStep) {
return new DevicePackageResult(false, errorMessage, failedStep, null, null); return error(errorMessage, failedStep, null);
}
public static DevicePackageResult error(String errorMessage, String failedStep, JsonNode limit) {
return new DevicePackageResult(false, errorMessage, failedStep, null, null, limit);
} }
} }

16
application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java

@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@ -170,8 +171,9 @@ class DefaultTbAiServiceTest {
} }
@ParameterizedTest @ParameterizedTest
@CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, GENERAL", "404, ITEM_NOT_FOUND", @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, PERMISSION_DENIED", "404, ITEM_NOT_FOUND",
"409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, GENERAL", "500, GENERAL", "0, GENERAL"}) "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, PERMISSION_DENIED", "500, GENERAL", "0, GENERAL",
"502, SERVICE_UNAVAILABLE", "503, SERVICE_UNAVAILABLE", "504, SERVICE_UNAVAILABLE"})
void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) { void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) {
// GIVEN // GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
@ -189,7 +191,7 @@ class DefaultTbAiServiceTest {
void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() { void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() {
// GIVEN // GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build()); given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).status(500).error("Upstream rejected").creditsUsed(42).build());
// WHEN // WHEN
Throwable thrown = catchThrowable(() -> service.process(call, user, true)); Throwable thrown = catchThrowable(() -> service.process(call, user, true));
@ -493,12 +495,12 @@ class DefaultTbAiServiceTest {
static List<Arguments> upstreamErrors() { static List<Arguments> upstreamErrors() {
return List.of( return List.of(
// PE-side inactivity timeout from the .timeout(...) operator // PE-side inactivity timeout from the .timeout(...) operator
arguments(new TimeoutException("inactivity"), "Request timed out"), arguments(new TimeoutException("inactivity"), TbAiOperations.TIMED_OUT_MESSAGE),
// the AI channel cannot be opened or closed before the turn started // the AI channel cannot be opened or closed before the turn started
arguments(new TbAiChannelUnavailableException("Connection refused", null), "Service unavailable"), arguments(new TbAiChannelUnavailableException("Connection refused", null), TbAiOperations.UNAVAILABLE_MESSAGE),
// the channel handshake was refused: the reason phrase is shown // the channel handshake was refused: the reason phrase is shown
arguments(new TbAiChannelRejectedException("Unauthorized"), "Unauthorized"), arguments(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED), "Unauthorized"),
arguments(new TbAiChannelRejectedException("Forbidden"), "Forbidden"), arguments(new TbAiChannelRejectedException(HttpStatus.FORBIDDEN), "Forbidden"),
// any other unexpected throwable // any other unexpected throwable
arguments(new RuntimeException("boom"), "Internal error") arguments(new RuntimeException("boom"), "Internal error")
); );

30
application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java

@ -17,6 +17,9 @@ import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiTransport; import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext; import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
@ -53,12 +56,14 @@ class DefaultAiChatServiceTest {
TbAiOperations operations; TbAiOperations operations;
@Mock @Mock
TbAiTransport tbAiTransport; TbAiTransport tbAiTransport;
@Mock
RateLimitService rateLimitService;
DefaultAiChatService service; DefaultAiChatService service;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
service = new DefaultAiChatService(tbAiService, tbAiTransport, operations); service = new DefaultAiChatService(tbAiService, tbAiTransport, operations, rateLimitService);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse); .thenReturn(tbAiResponse);
} }
@ -182,6 +187,9 @@ class DefaultAiChatServiceTest {
.event("assistantMessage") .event("assistantMessage")
.data("{\"message\":\"ok\"}") .data("{\"message\":\"ok\"}")
.build()); .build());
TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
given(user.getTenantId()).willReturn(tenantId);
given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(true);
given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream); given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream);
var clientOrigin = "https://tb.example.com"; var clientOrigin = "https://tb.example.com";
var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
@ -200,6 +208,26 @@ class DefaultAiChatServiceTest {
then(tbAiService).shouldHaveNoMoreInteractions(); then(tbAiService).shouldHaveNoMoreInteractions();
} }
@Test
void shouldAnswerWithRateLimitedError_whenTenantExceedsAiChatRequestsLimit() {
// GIVEN
UUID chatId = UUID.randomUUID();
TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
given(user.getTenantId()).willReturn(tenantId);
given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false);
// WHEN
var events = service.sendChatMessage(chatId, sendMessageBody("And how many assets?", "DEVICE_LIST"),
"tb-access-token", "en-US", "https://tb.example.com", user).collectList().block();
// THEN
assertThat(events).hasSize(1);
assertThat(events.get(0).event()).isEqualTo("error");
assertThat(events.get(0).data()).isEqualTo("{\"message\":\"Rate limit exceeded\",\"code\":\"RATE_LIMITED\"}");
then(tbAiService).shouldHaveNoInteractions();
then(tbAiTransport).shouldHaveNoInteractions();
}
@Test @Test
void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() { void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() {
// GIVEN // GIVEN

25
application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java

@ -22,7 +22,10 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperation;
@ -58,6 +61,10 @@ class DefaultAiSolutionServiceTest {
TbAiOperations operations; TbAiOperations operations;
@Mock @Mock
SecurityUser user; SecurityUser user;
@Mock
RateLimitService rateLimitService;
TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
String clientOrigin = "https://tb.example.com"; String clientOrigin = "https://tb.example.com";
@ -65,7 +72,9 @@ class DefaultAiSolutionServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
service = new DefaultAiSolutionService(tbAiService, operations); service = new DefaultAiSolutionService(tbAiService, operations, rateLimitService);
lenient().when(user.getTenantId()).thenReturn(tenantId);
lenient().when(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).thenReturn(true);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse); .thenReturn(tbAiResponse);
} }
@ -136,6 +145,20 @@ class DefaultAiSolutionServiceTest {
then(tbAiService).shouldHaveNoInteractions(); then(tbAiService).shouldHaveNoInteractions();
} }
@Test
void shouldRefuseWithTooManyRequestsWithoutCallingTheAiService_whenTheTenantIsOverTheChatRequestsLimit() {
// GIVEN
given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false);
// WHEN
Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, "Add humidity", List.of(), user));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Rate limit exceeded");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS);
then(tbAiService).shouldHaveNoInteractions();
}
@ParameterizedTest @ParameterizedTest
@EnumSource(SolutionStep.class) @EnumSource(SolutionStep.class)
void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) { void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) {

6
application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java

@ -189,7 +189,8 @@ class ChannelTbAiOperationsTest {
// THEN // THEN
assertThat(response.isSuccess()).isFalse(); assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable"); assertThat(response.getStatus()).isEqualTo(503);
assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
} }
@ -239,7 +240,8 @@ class ChannelTbAiOperationsTest {
// THEN // THEN
assertThat(response.isSuccess()).isFalse(); assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable"); assertThat(response.getStatus()).isEqualTo(503);
assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
assertThat(server.connections.get()).isEqualTo(1); assertThat(server.connections.get()).isEqualTo(1);
} }

81
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java

@ -7,17 +7,24 @@ import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.ai.common.client.TbAiTokenFactory;
import org.thingsboard.ai.common.data.usage.RateLimitScope;
import org.thingsboard.ai.common.data.usage.RateLimitedApi;
import org.thingsboard.ai.common.data.user.ProfileConfig;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -28,6 +35,8 @@ import static org.mockito.Mockito.mock;
class TbAiChannelPoolTest { class TbAiChannelPoolTest {
static final String TB_VERSION = "4.4.0"; static final String TB_VERSION = "4.4.0";
static final TbAiTokenFactory TOKEN_FACTORY = new TbAiTokenFactory("test", Base64.getEncoder()
.encodeToString("tb-ai-channel-pool-test-signing-key-".repeat(2).getBytes(StandardCharsets.UTF_8)), Duration.ofMinutes(60));
AtomicLong now = new AtomicLong(1_000_000_000L); AtomicLong now = new AtomicLong(1_000_000_000L);
FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {}); FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {});
@ -246,6 +255,68 @@ class TbAiChannelPoolTest {
await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0); await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0);
} }
@Test
void shouldRetireIdleChannel_whenTheTokenCarriesOtherLimits() {
// GIVEN
pool = pool(10);
SecurityUser user = user();
AtomicReference<String> token = new AtomicReference<>(token("10:60", "198.51.100.10"));
TbAiTurnContext context = context(user, token);
TbAiPooledConnection before = join(pool.acquire(context, false));
before.unreserve(now.get());
// WHEN
token.set(token("1:60", "198.51.100.10"));
TbAiPooledConnection after = join(pool.acquire(context, false));
// THEN
assertThat(after).isNotSameAs(before);
assertThat(server.connections.get()).isEqualTo(2);
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
}
@Test
void shouldFinishTheRunningCallOnAStaleChannel_thenCloseIt() {
// GIVEN
pool = pool(10);
AtomicReference<String> token = new AtomicReference<>(token("10:60", "198.51.100.10"));
TbAiTurnContext context = context(user(), token);
TbAiPooledConnection busy = join(pool.acquire(context, false));
// WHEN
token.set(token("1:60", "198.51.100.10"));
TbAiPooledConnection next = join(pool.acquire(context, false));
int openWhileBusy = server.openConnections.get();
busy.unreserve(now.get());
// THEN
assertThat(next).isNotSameAs(busy);
assertThat(openWhileBusy).isEqualTo(2);
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
}
@Test
void shouldKeepChannel_whenOnlyTheClientAddressChanged() {
// GIVEN
pool = pool(10);
AtomicReference<String> token = new AtomicReference<>(token("10:60", "198.51.100.10"));
TbAiTurnContext context = context(user(), token);
TbAiPooledConnection desktop = join(pool.acquire(context, false));
desktop.unreserve(now.get());
// WHEN
token.set(token("10:60", "203.0.113.20"));
TbAiPooledConnection mobile = join(pool.acquire(context, false));
mobile.unreserve(now.get());
token.set(token("10:60", "198.51.100.10"));
TbAiPooledConnection desktopAgain = join(pool.acquire(context, false));
// THEN
assertThat(mobile).isSameAs(desktop);
assertThat(desktopAgain).isSameAs(desktop);
assertThat(server.connections.get()).isEqualTo(1);
}
TbAiChannelPool pool(int maxConnections) { TbAiChannelPool pool(int maxConnections) {
return new TbAiChannelPool(server.client(), TB_VERSION, maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false); return new TbAiChannelPool(server.client(), TB_VERSION, maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false);
} }
@ -265,4 +336,14 @@ class TbAiChannelPoolTest {
return new TbAiTurnContext(user, null, null, () -> "token", origin); return new TbAiTurnContext(user, null, null, () -> "token", origin);
} }
static TbAiTurnContext context(SecurityUser user, AtomicReference<String> token) {
return new TbAiTurnContext(user, null, null, token::get, "https://tb.example.com");
}
static String token(String chatRequestsLimit, String clientAddress) {
ProfileConfig profileConfig = new ProfileConfig();
profileConfig.setRateLimits(Map.of(RateLimitedApi.AI_CHAT_REQUESTS, Map.of(RateLimitScope.TENANT, chatRequestsLimit)));
return TOKEN_FACTORY.createToken(UUID.randomUUID().toString(), profileConfig, Map.of("clientAddress", clientAddress));
}
} }

7
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport; package org.thingsboard.server.service.ai.transport;
import org.springframework.http.HttpStatus;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
@ -50,19 +51,21 @@ class TbAiOperationsTest {
// THEN // THEN
assertThat(response.isSuccess()).isFalse(); assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable"); assertThat(response.getStatus()).isEqualTo(503);
assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
} }
@Test @Test
void shouldReturnRejection_whenChannelHandshakeIsRefused() { void shouldReturnRejection_whenChannelHandshakeIsRefused() {
// GIVEN // GIVEN
given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException("Unauthorized")); given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED));
// WHEN // WHEN
TbAiResponse response = operations.execute(operation, context); TbAiResponse response = operations.execute(operation, context);
// THEN // THEN
assertThat(response.isSuccess()).isFalse(); assertThat(response.isSuccess()).isFalse();
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getError()).isEqualTo("Unauthorized"); assertThat(response.getError()).isEqualTo("Unauthorized");
} }

23
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java

@ -14,7 +14,6 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
import java.time.Duration; import java.time.Duration;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -71,7 +70,7 @@ class TbAiPooledConnectionTest {
} }
@Test @Test
void shouldSendHelloWithoutCapabilities_whenSessionOpens() { void shouldSendHelloWithItsCapabilities_whenSessionOpens() {
// GIVEN // GIVEN
TbAiPooledConnection connection = connection(); TbAiPooledConnection connection = connection();
ChannelSession session = openSession(); ChannelSession session = openSession();
@ -83,12 +82,30 @@ class TbAiPooledConnectionTest {
// THEN // THEN
then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO, then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO,
codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, List.of(), "https://tb.example.com", null)))); codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null))));
then(session).should(never()).close(anyInt(), anyString()); then(session).should(never()).close(anyInt(), anyString());
assertThat(connection.ready()).isCompletedWithValue(connection); assertThat(connection.ready()).isCompletedWithValue(connection);
assertThat(connection.maxFrameBytes()).isEqualTo(1024); assertThat(connection.maxFrameBytes()).isEqualTo(1024);
} }
@Test
void shouldBeStale_whenTheCallerHoldsOtherLimits() {
// GIVEN
TbAiPooledConnection connection = connection();
connection.handshakeLimits("limits-before-the-profile-change");
// WHEN-THEN
assertThat(connection.isStaleFor("limits-after-the-profile-change")).isTrue();
assertThat(connection.isStaleFor("limits-before-the-profile-change")).isFalse();
assertThat(connection.isStaleFor(null)).isFalse();
}
@Test
void shouldNotBeStale_whenItsHandshakeLimitsAreUnknown() {
// WHEN-THEN
assertThat(connection().isStaleFor("any-limits")).isFalse();
}
TbAiPooledConnection connection() { TbAiPooledConnection connection() {
return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime()); return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime());
} }

28
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java

@ -47,6 +47,7 @@ import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode;
import org.thingsboard.server.common.data.subscription.SubscriptionEntry;
import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
@ -69,6 +70,7 @@ import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import org.thingsboard.server.exception.EntitiesLimitExceededException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -870,6 +872,32 @@ class DefaultDevicePackageServiceTest {
.isEqualTo("Failed to save the device package"); .isEqualTo("Failed to save the device package");
} }
@Test
void limitOf_givesTheLimitResponseBody_whenAStepHitsASubscriptionLimit() {
JsonNode limit = DefaultDevicePackageService.limitOf(new RuntimeException("step failed", new SubscriptionException(
"Maximum allowed devices limit reached!", SubscriptionErrorCode.LIMIT_REACHED, SubscriptionEntry.DEVICE_COUNT, 5)));
assertThat(limit.get("errorCode").asInt()).isEqualTo(40);
assertThat(limit.get("message").asText()).isEqualTo("Maximum allowed devices limit reached!");
assertThat(limit.get("subscriptionErrorCode").asText()).isEqualTo("LIMIT_REACHED");
assertThat(limit.get("subscriptionEntry").asText()).isEqualTo("DEVICE_COUNT");
assertThat(limit.at("/subscriptionValue/value").asLong()).isEqualTo(5);
}
@Test
void limitOf_givesTheLimitResponseBody_whenAStepHitsATenantProfileLimit() {
JsonNode limit = DefaultDevicePackageService.limitOf(new EntitiesLimitExceededException(TenantId.SYS_TENANT_ID, EntityType.DASHBOARD, 10));
assertThat(limit.get("errorCode").asInt()).isEqualTo(41);
assertThat(limit.get("entityType").asText()).isEqualTo("DASHBOARD");
assertThat(limit.get("limit").asLong()).isEqualTo(10);
}
@Test
void limitOf_givesNothing_whenTheFailureIsNotALimit() {
assertThat(DefaultDevicePackageService.limitOf(new DataValidationException("Device with such name already exists!"))).isNull();
}
@Test @Test
void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() { void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() {
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode device = JacksonUtil.newObjectNode().put("id", "123");

3
common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java

@ -22,7 +22,8 @@ public enum ThingsboardErrorCode {
ENTITIES_LIMIT_EXCEEDED(41), ENTITIES_LIMIT_EXCEEDED(41),
PASSWORD_VIOLATION(45), PASSWORD_VIOLATION(45),
DATABASE(46), DATABASE(46),
SETUP_INCOMPLETE(47); SETUP_INCOMPLETE(47),
SERVICE_UNAVAILABLE(48);
private int errorCode; private int errorCode;

2
common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java

@ -57,7 +57,7 @@ public enum LimitedApi {
WS_SUBSCRIPTIONS("WS subscriptions", false), WS_SUBSCRIPTIONS("WS subscriptions", false),
CALCULATED_FIELD_DEBUG_EVENTS("calculated field debug events", true), CALCULATED_FIELD_DEBUG_EVENTS("calculated field debug events", true),
TRENDZ_PUBLIC_SYNC("Trendz sync from public endpoint", false), TRENDZ_PUBLIC_SYNC("Trendz sync from public endpoint", false),
AI_CHAT_REQUESTS("AI chat requests", true); AI_CHAT_REQUESTS(DefaultTenantProfileConfiguration::getAiChatRequestsPerTenantRateLimit, "AI chat requests", true, true);
private final Function<DefaultTenantProfileConfiguration, String> configExtractor; private final Function<DefaultTenantProfileConfiguration, String> configExtractor;
private final boolean perTenant; private final boolean perTenant;

29
common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java

@ -12,6 +12,7 @@ import org.thingsboard.server.common.data.id.EntityGroupId;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -40,6 +41,8 @@ public final class MergedUserPermissions implements Serializable {
@Schema(description = "Map of read entity time-series permissions per resource. Used on the UI to enable/disable certain tabs.") @Schema(description = "Map of read entity time-series permissions per resource. Used on the UI to enable/disable certain tabs.")
private final Map<Resource, MergedGroupTypePermissionInfo> readTsPermissions; private final Map<Resource, MergedGroupTypePermissionInfo> readTsPermissions;
public static final Set<Resource> AI_RESOURCES = Set.of(Resource.AI, Resource.AI_MODEL);
public static final MergedUserPermissions ALL = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); public static final MergedUserPermissions ALL = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap());
@JsonCreator @JsonCreator
@ -134,6 +137,32 @@ public final class MergedUserPermissions implements Serializable {
return hasGenericResourcePermission(resource, operation) || hasGenericAllPermission(operation); return hasGenericResourcePermission(resource, operation) || hasGenericAllPermission(operation);
} }
/**
* True when the user has the operation on every resource except the AI ones ({@link #AI_RESOURCES}): either through
* {@link Resource#ALL}, or resource by resource, as a role that allows everything but excludes AI is merged.
*/
public boolean hasGenericPermissionExceptAi(Operation operation) {
if (hasGenericAllPermission(operation)) {
return true;
}
return Arrays.stream(Resource.values())
.filter(resource -> resource != Resource.ALL && !AI_RESOURCES.contains(resource))
.allMatch(resource -> hasEveryOperation(resource, operation));
}
private boolean hasEveryOperation(Resource resource, Operation operation) {
Set<Operation> valid = Resource.operationsByResource.get(resource);
if (valid == null) {
return true;
}
if (operation != Operation.ALL) {
return !valid.contains(operation) || hasGenericResourcePermission(resource, operation);
}
List<Operation> required = valid.stream().filter(op -> op != Operation.ALL).toList();
return required.isEmpty() ? hasGenericResourcePermission(resource, Operation.ALL)
: required.stream().allMatch(op -> hasGenericResourcePermission(resource, op));
}
private boolean hasGenericAllPermission(Operation operation) { private boolean hasGenericAllPermission(Operation operation) {
Set<Operation> operations = genericPermissions.get(Resource.ALL); Set<Operation> operations = genericPermissions.get(Resource.ALL);
return operations != null && checkOperation(operations, operation); return operations != null && checkOperation(operations, operation);

4
common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java

@ -80,7 +80,9 @@ class LimitedApiTest {
Map.entry(LimitedApi.INTEGRATION_MSGS_PER_DEVICE, () -> Map.entry(LimitedApi.INTEGRATION_MSGS_PER_DEVICE, () ->
verify(config).getIntegrationMsgsPerDeviceRateLimit()), verify(config).getIntegrationMsgsPerDeviceRateLimit()),
Map.entry(LimitedApi.INTEGRATION_MSGS_PER_ASSET, () -> Map.entry(LimitedApi.INTEGRATION_MSGS_PER_ASSET, () ->
verify(config).getIntegrationMsgsPerAssetRateLimit()) verify(config).getIntegrationMsgsPerAssetRateLimit()),
Map.entry(LimitedApi.AI_CHAT_REQUESTS, () ->
verify(config).getAiChatRequestsPerTenantRateLimit())
); );
Set<LimitedApi> expected = verifierMap.keySet(); Set<LimitedApi> expected = verifierMap.keySet();

75
common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java

@ -0,0 +1,75 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.common.data.permission;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
class MergedUserPermissionsTest {
@Test
void shouldAllowEverythingExceptAi_whenTheRoleAllowsAll() {
MergedUserPermissions permissions = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap());
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue();
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue();
}
@Test
void shouldAllowEverythingExceptAi_whenAllIsAllowedAndTheAiResourcesAreExcluded() {
MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.ALL), Collections.emptyMap());
assertThat(permissions.hasGenericPermission(Resource.ALL, Operation.ALL)).isFalse();
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue();
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue();
}
@Test
void shouldNotAllowEverything_whenAnotherResourceIsExcluded() {
Map<Resource, Set<Operation>> generic = expandedExceptAi(Operation.ALL);
generic.get(Resource.DEVICE).remove(Operation.WRITE);
MergedUserPermissions permissions = new MergedUserPermissions(generic, Collections.emptyMap());
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse();
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue();
}
@Test
void shouldAllowReadOnly_whenReadIsAllowedOnEverythingExceptAi() {
MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.READ), Collections.emptyMap());
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue();
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse();
}
static Map<Resource, Set<Operation>> expandedExceptAi(Operation allowed) {
Map<Resource, Set<Operation>> generic = new HashMap<>();
for (Resource resource : Resource.values()) {
Set<Operation> valid = Resource.operationsByResource.get(resource);
if (resource == Resource.ALL || MergedUserPermissions.AI_RESOURCES.contains(resource) || valid == null) {
continue;
}
Set<Operation> operations = new HashSet<>(valid);
if (allowed == Operation.ALL) {
if (operations.size() > 1) {
operations.remove(Operation.ALL);
}
} else {
operations.retainAll(Set.of(allowed));
}
if (!operations.isEmpty()) {
generic.put(resource, operations);
}
}
return generic;
}
}

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

@ -12,6 +12,8 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@ -145,6 +147,25 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
return findByIdAsync(tenantId, key); return findByIdAsync(tenantId, key);
} }
private static final String SEVERITY_PROPERTY = "severity";
private static final String SEVERITY_RANK = "(case a.severity"
+ Arrays.stream(AlarmSeverity.values())
.map(severity -> " when " + AlarmSeverity.class.getName() + "." + severity.name() + " then " + severity.ordinal())
.collect(Collectors.joining())
+ " else " + AlarmSeverity.values().length + " end)";
private static Pageable toAlarmPageable(PageLink pageLink) {
Pageable pageable = DaoUtil.toPageable(pageLink);
if (pageable.getSort().getOrderFor(SEVERITY_PROPERTY) == null) {
return pageable;
}
List<Sort.Order> orders = pageable.getSort().stream()
.map(order -> SEVERITY_PROPERTY.equals(order.getProperty()) ? JpaSort.unsafe(order.getDirection(), SEVERITY_RANK).iterator().next() : order)
.toList();
return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders));
}
@Override @Override
public PageData<AlarmInfo> findAlarms(TenantId tenantId, AlarmQuery query) { public PageData<AlarmInfo> findAlarms(TenantId tenantId, AlarmQuery query) {
log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink()); log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink());
@ -164,7 +185,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} else { } else {
@ -179,7 +200,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} }
@ -201,7 +222,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} }
@ -230,7 +251,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} else { } else {
@ -247,7 +268,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} }
@ -273,7 +294,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(), asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()), DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(), query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink()) toAlarmPageable(query.getPageLink())
) )
); );
} }

6
dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java

@ -31,6 +31,7 @@ import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.dao.sql.citus.CitusSettings; import org.thingsboard.server.dao.sql.citus.CitusSettings;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -47,7 +48,10 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository {
private static final Map<String, String> alarmFieldColumnMap = new HashMap<>(); private static final Map<String, String> alarmFieldColumnMap = new HashMap<>();
private static final String SEVERITY_RANK = "case a." + ModelConstants.ALARM_SEVERITY_PROPERTY private static final String SEVERITY_RANK = "case a." + ModelConstants.ALARM_SEVERITY_PROPERTY
+ " when 'CRITICAL' then 0 when 'MAJOR' then 1 when 'MINOR' then 2 when 'WARNING' then 3 when 'INDETERMINATE' then 4 else 5 end"; + Arrays.stream(AlarmSeverity.values())
.map(severity -> " when '" + severity.name() + "' then " + severity.ordinal())
.collect(Collectors.joining())
+ " else " + AlarmSeverity.values().length + " end";
private static final Set<String> ALARM_TABLE_SORT_COLUMNS = Set.of(ModelConstants.CREATED_TIME_PROPERTY, ModelConstants.ALARM_ACK_TS_PROPERTY, 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_CLEAR_TS_PROPERTY, ModelConstants.ALARM_ASSIGN_TS_PROPERTY, ModelConstants.ALARM_END_TS_PROPERTY,

21
dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java

@ -64,6 +64,7 @@ import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.DataValidationException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -834,6 +835,26 @@ public class AlarmServiceTest extends AbstractServiceTest {
pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC)); pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC));
Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery)
.getData().stream().map(AlarmData::getId).toList()); .getData().stream().map(AlarmData::getId).toList());
pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC));
pageLink.setTextSearch("Severity");
Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery)
.getData().stream().map(AlarmData::getId).toList());
Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId()))
.getData().stream().map(AlarmData::getId).toList());
List<String> types = Arrays.stream(AlarmSeverity.values()).map(severity -> "Severity " + severity).toList();
for (SortOrder.Direction direction : SortOrder.Direction.values()) {
List<AlarmId> expected = direction == SortOrder.Direction.ASC ? byPriority : byPriority.reversed();
TimePageLink timePageLink = new TimePageLink(10, 0, null, new SortOrder("severity", direction), null, null);
Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder()
.affectedEntityId(device.getId()).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList());
Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder()
.typeList(types).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList());
Assert.assertEquals(expected, alarmService.findAlarms(tenantId, AlarmQuery.builder()
.affectedEntityId(device.getId()).pageLink(new TimePageLink(10, 0, "Severity", new SortOrder("severity", direction), null, null)).build())
.getData().stream().map(AlarmInfo::getId).toList());
}
} }
private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) {

1
ui-ngx/package.json

@ -59,6 +59,7 @@
"angular2-hotkeys": "^16.0.1", "angular2-hotkeys": "^16.0.1",
"canvas-gauges": "^2.1.7", "canvas-gauges": "^2.1.7",
"dayjs": "1.11.23", "dayjs": "1.11.23",
"dompurify": "^3.3.3",
"echarts": "https://github.com/thingsboard/echarts/archive/5.5.4-TB.tar.gz", "echarts": "https://github.com/thingsboard/echarts/archive/5.5.4-TB.tar.gz",
"exceljs-hardened": "~5.1.0", "exceljs-hardened": "~5.1.0",
"flag-icons": "7.6.0", "flag-icons": "7.6.0",

36
ui-ngx/src/app/core/http/user-permissions.service.ts

@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators'; import { distinctUntilChanged, map, tap } from 'rxjs/operators';
import { import {
AllowedPermissionsInfo, AllowedPermissionsInfo,
groupResourceByGroupType, groupResourceByGroupType,
@ -19,9 +20,11 @@ import { isArray } from '@core/utils';
import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { getCurrentAuthState, selectAuth } from '@core/auth/auth.selectors';
import { Authority } from '@shared/models/authority.enum'; import { Authority } from '@shared/models/authority.enum';
const AI_RESOURCES: Resource[] = [Resource.AI, Resource.AI_MODEL];
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@ -35,6 +38,11 @@ export class UserPermissionsService {
private userPermissions: MergedUserPermissions; private userPermissions: MergedUserPermissions;
private userOwnerId: EntityId; private userOwnerId: EntityId;
readonly aiAvailable = toSignal(inject(Store<AppState>).select(selectAuth).pipe(
map(() => this.isAiAvailable()),
distinctUntilChanged()
), {initialValue: false});
constructor( constructor(
private http: HttpClient, private http: HttpClient,
private store: Store<AppState> private store: Store<AppState>
@ -123,6 +131,28 @@ export class UserPermissionsService {
} }
} }
public hasGenericPermissionExceptAi(operation: Operation): boolean {
if (!this.userPermissions) {
return false;
}
if (this.hasGenericAllPermission(Resource.ALL, operation)) {
return true;
}
return Object.keys(this.operationsByResource ?? {})
.filter(resource => resource !== Resource.ALL && !AI_RESOURCES.includes(resource as Resource))
.every(resource => this.hasEveryOperation(resource as Resource, operation));
}
private hasEveryOperation(resource: Resource, operation: Operation): boolean {
const valid = this.operationsByResource[resource] ?? [];
if (operation !== Operation.ALL) {
return !valid.includes(operation) || this.hasGenericResourcePermission(resource, operation);
}
const required = valid.filter(op => op !== Operation.ALL);
return required.length ? required.every(op => this.hasGenericResourcePermission(resource, op))
: this.hasGenericResourcePermission(resource, Operation.ALL);
}
public isAiEnabled(): boolean { public isAiEnabled(): boolean {
return getCurrentAuthState(this.store).aiEnabled; return getCurrentAuthState(this.store).aiEnabled;
} }

32
ui-ngx/src/app/core/interceptors/global-http-interceptor.ts

@ -1,18 +1,18 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpErrorResponse, HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable'; import { Observable } from 'rxjs/internal/Observable';
import { DOCUMENT, Inject, Injectable } from '@angular/core'; import { DOCUMENT, Inject, Injectable } from '@angular/core';
import { AuthService } from '@core/auth/auth.service'; import { AuthService } from '@core/auth/auth.service';
import { Constants } from '@shared/models/constants'; import { Constants } from '@shared/models/constants';
import { catchError, delay, finalize, mergeMap, switchMap } from 'rxjs/operators'; import { catchError, delay, finalize, mergeMap, switchMap, tap } from 'rxjs/operators';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { InterceptorConfig } from './interceptor-config'; import { InterceptorConfig } from './interceptor-config';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { ActionLoadFinish, ActionLoadStart } from './load.actions'; import { ActionLoadFinish, ActionLoadStart } from './load.actions';
import { ActionNotificationShow } from '@app/core/notification/notification.actions'; import { ActionNotificationHide, ActionNotificationShow } from '@app/core/notification/notification.actions';
import { DialogService } from '@core/services/dialog.service'; import { DialogService } from '@core/services/dialog.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { parseHttpErrorMessage } from '@core/utils'; import { parseHttpErrorMessage } from '@core/utils';
@ -23,6 +23,8 @@ import { isSetupIncompleteError } from '@shared/models/system-setup.models';
const tmpHeaders = {}; const tmpHeaders = {};
const CONNECTION_ERROR = 'Unable to connect';
@Injectable() @Injectable()
export class GlobalHttpInterceptor implements HttpInterceptor { export class GlobalHttpInterceptor implements HttpInterceptor {
@ -31,6 +33,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
private activeRequests = 0; private activeRequests = 0;
private connectionErrorShown = false;
constructor( constructor(
private store: Store<AppState>, private store: Store<AppState>,
private dialogService: DialogService, private dialogService: DialogService,
@ -39,7 +43,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
private sanitizer: DomSanitizer, private sanitizer: DomSanitizer,
private systemSetupService: SystemSetupService, private systemSetupService: SystemSetupService,
@Inject(DOCUMENT) private document: Document @Inject(DOCUMENT) private document: Document
) {} ) {
this.document.defaultView?.addEventListener('online', () => this.connectionRestored());
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith('/api/')) { if (req.url.startsWith('/api/')) {
@ -80,6 +86,11 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
private handleRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { private handleRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe( return next.handle(req).pipe(
tap(event => {
if (event.type === HttpEventType.ResponseHeader || event.type === HttpEventType.Response) {
this.connectionRestored();
}
}),
catchError((err) => { catchError((err) => {
const errorResponse = err as HttpErrorResponse; const errorResponse = err as HttpErrorResponse;
return this.handleResponseError(req, next, errorResponse); return this.handleResponseError(req, next, errorResponse);
@ -92,6 +103,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
const ignoreErrors = config.ignoreErrors; const ignoreErrors = config.ignoreErrors;
const resendRequest = config.resendRequest; const resendRequest = config.resendRequest;
const errorCode = errorResponse.error ? errorResponse.error.errorCode : null; const errorCode = errorResponse.error ? errorResponse.error.errorCode : null;
if (errorResponse.status > 0) {
this.connectionRestored();
}
if (errorResponse.error && errorResponse.error.refreshTokenPending || if (errorResponse.error && errorResponse.error.refreshTokenPending ||
errorResponse.status === 401 && req.url !== Constants.entryPoints.tokenRefresh) { errorResponse.status === 401 && req.url !== Constants.entryPoints.tokenRefresh) {
if (errorResponse.error && errorResponse.error.refreshTokenPending || if (errorResponse.error && errorResponse.error.refreshTokenPending ||
@ -122,7 +136,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
this.handleLock(errorResponse.error); this.handleLock(errorResponse.error);
} else if (errorResponse.status === 0 || errorResponse.status === -1) { } else if (errorResponse.status === 0 || errorResponse.status === -1) {
if (!ignoreErrors) { if (!ignoreErrors) {
this.showError('Unable to connect'); this.connectionErrorShown = true;
this.showError(CONNECTION_ERROR);
} }
} else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) { } else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) {
if (errorResponse.status === 404) { if (errorResponse.status === 404) {
@ -218,6 +233,13 @@ export class GlobalHttpInterceptor implements HttpInterceptor {
} }
} }
private connectionRestored(): void {
if (this.connectionErrorShown) {
this.connectionErrorShown = false;
this.store.dispatch(new ActionNotificationHide({message: CONNECTION_ERROR}));
}
}
private showError(error: string, timeout: number = 0) { private showError(error: string, timeout: number = 0) {
setTimeout(() => { setTimeout(() => {
this.store.dispatch(new ActionNotificationShow({message: error, type: 'error'})); this.store.dispatch(new ActionNotificationShow({message: error, type: 'error'}));

1
ui-ngx/src/app/core/notification/notification.models.ts

@ -26,4 +26,5 @@ export class NotificationMessage {
export class HideNotification { export class HideNotification {
target?: string; target?: string;
message?: string;
} }

25
ui-ngx/src/app/core/services/ai-assistant-panel.service.ts

@ -84,6 +84,9 @@ export class AiAssistantPanelService implements OnDestroy {
).subscribe(event => { ).subscribe(event => {
const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects); const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects);
this._suppressed.set(suppressed); this._suppressed.set(suppressed);
if (suppressed && !AiAssistantPanelService.onAiPage(event.urlAfterRedirects)) {
this._composed.set(null);
}
const openHere = this._openOnArrival && !suppressed; const openHere = this._openOnArrival && !suppressed;
if (!suppressed) { if (!suppressed) {
this._openOnArrival = false; this._openOnArrival = false;
@ -128,6 +131,11 @@ export class AiAssistantPanelService implements OnDestroy {
this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null); this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null);
} }
private static onAiPage(url: string): boolean {
const path = (url || '/').split(/[?#]/)[0];
return path === '/ai-assistant' || path.startsWith('/ai-assistant/');
}
private static withoutPanel(url: string): boolean { private static withoutPanel(url: string): boolean {
const path = (url || '/').split(/[?#]/)[0]; const path = (url || '/').split(/[?#]/)[0];
return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/')); return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/'));
@ -382,22 +390,19 @@ export class AiAssistantPanelService implements OnDestroy {
this._open.set(true); this._open.set(true);
} }
private _composed = signal<{text: string; fresh: boolean} | null>(null); private _composed = signal<string | null>(null);
readonly composed = this._composed.asReadonly(); readonly composed = this._composed.asReadonly();
compose(text: string): void { compose(text: string): void {
if (this._suppressed()) { this._composed.set(text);
return; if (!this._suppressed()) {
this.openPanel();
} else if (!AiAssistantPanelService.onAiPage(this.router.url)) {
this.router.navigateByUrl('/ai-assistant');
} }
this._composed.set({text, fresh: !this._open()});
this.openPanel();
}
composesFresh(): boolean {
return !!this._composed()?.fresh;
} }
takeComposed(): {text: string; fresh: boolean} | null { takeComposed(): string | null {
const composed = this._composed(); const composed = this._composed();
this._composed.set(null); this._composed.set(null);
return composed; return composed;

13
ui-ngx/src/app/core/services/ai-solutions.service.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { DestroyRef, inject, Injectable, signal } from '@angular/core'; import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
@ -182,6 +182,16 @@ export class AiSolutionsService {
return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null; return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null;
} }
needsAttention(solution: SolutionInfo): boolean {
const level = this.levelOf(solution);
if (this._needs().has(solution.id)) {
return level === 'error';
}
return level === 'needs' || level === 'error';
}
readonly attention = computed(() => this._solutions().filter(solution => this.needsAttention(solution)));
tipOf(solution: SolutionInfo, open = false): string { tipOf(solution: SolutionInfo, open = false): string {
const level = this.levelOf(solution, open); const level = this.levelOf(solution, open);
if (!level) { if (!level) {
@ -203,6 +213,7 @@ export class AiSolutionsService {
const solution: SolutionInfo = { const solution: SolutionInfo = {
id: info.id, id: info.id,
createdTime: info.createdTime, createdTime: info.createdTime,
updatedTime: this.find(info.id)?.updatedTime ?? info.createdTime,
solutionTitle: info.data?.solutionTitle || info.data?.aiSolutionTitle || this.find(info.id)?.solutionTitle || '', solutionTitle: info.data?.solutionTitle || info.data?.aiSolutionTitle || this.find(info.id)?.solutionTitle || '',
built: !!info.metadata?.built, built: !!info.metadata?.built,
installed: !!info.metadata?.installed installed: !!info.metadata?.installed

2
ui-ngx/src/app/core/services/menu.models.ts

@ -1579,7 +1579,7 @@ const menuFilters = new Map<MenuId, MenuFilter>([
[ [
MenuId.iot_hub, (authState, userPermissionsService) => MenuId.iot_hub, (authState, userPermissionsService) =>
authState.authUser.authority === Authority.TENANT_ADMIN && authState.authUser.authority === Authority.TENANT_ADMIN &&
userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL) userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL)
], ],
[ [
MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable() MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable()

2
ui-ngx/src/app/core/services/tour.service.ts

@ -32,7 +32,7 @@ export class TourService {
private offered = false; private offered = false;
aiAvailable(): boolean { aiAvailable(): boolean {
return this.userPermissions.isAiAvailable(); return this.userPermissions.aiAvailable();
} }
offerWelcome(): void { offerWelcome(): void {

16
ui-ngx/src/app/core/utils.ts

@ -1283,3 +1283,19 @@ export const objectRequired = (): ValidatorFn => {
return null; return null;
}; };
} }
export function escapeHtml(value: string): string {
return value.replace(/[&<>]/g, ch => ch === '&' ? '&amp;' : ch === '<' ? '&lt;' : '&gt;');
}
export function escapeHtmlAttr(value: string): string {
return value.replace(/[&<>"']/g, ch => {
switch (ch) {
case '&': return '&amp;';
case '<': return '&lt;';
case '>': return '&gt;';
case '"': return '&quot;';
default: return '&#39;';
}
});
}

7
ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss

@ -0,0 +1,7 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// Widths at which the AI chat drops secondary text. The chat head's narrow width used by the
// component code is AI_NARROW_HEAD_WIDTH in ai-breakpoints.ts.
$ai-head-status-hidden-below: 400px;
$ai-composer-auto-label-max: 400px;

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

@ -216,7 +216,7 @@
} }
@case ('markdown') { @case ('markdown') {
<div class="k-detail-md"> <div class="k-detail-md">
<tb-markdown usePlainMarkdown [highlight]="false" [data]="block.text"></tb-markdown> <tb-markdown usePlainMarkdown sanitizeHtml [highlight]="false" [data]="block.text"></tb-markdown>
</div> </div>
} }
@case ('images') { @case ('images') {

23
ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html

@ -52,14 +52,7 @@
</div> </div>
} }
@if (unchanged.length && showUnchanged) { @if (unchanged.length && showUnchanged) {
<div class="k-diff-same"> <ng-container *ngTemplateOutlet="unchangedFields"></ng-container>
@for (same of unchanged; track $index) {
<div class="k-diff-f">
<div class="k-diff-l">@if (same.labelCode) { <code>{{ same.label }}</code> } @else { {{ same.label }} }</div>
<div class="k-diff-v"><span class="k-diff-was">{{ same.value }}</span></div>
</div>
}
</div>
} }
</div> </div>
@if (unchanged.length) { @if (unchanged.length) {
@ -68,6 +61,10 @@
{{ (showUnchanged ? 'ai-assistant.review.hide-unchanged' : 'ai-assistant.review.unchanged') | translate: {count: unchanged.length} }} {{ (showUnchanged ? 'ai-assistant.review.hide-unchanged' : 'ai-assistant.review.unchanged') | translate: {count: unchanged.length} }}
</button> </button>
} }
} @else if (unchanged.length) {
<div class="k-diff">
<ng-container *ngTemplateOutlet="unchangedFields"></ng-container>
</div>
} }
<div class="k-actions"> <div class="k-actions">
<button mat-flat-button type="button" [class.warn]="isDestructive" [disabled]="state === 'waiting' && busy" (click)="approve()"> <button mat-flat-button type="button" [class.warn]="isDestructive" [disabled]="state === 'waiting' && busy" (click)="approve()">
@ -96,3 +93,13 @@
} }
</div> </div>
} }
<ng-template #unchangedFields>
<div class="k-diff-same">
@for (same of unchanged; track $index) {
<div class="k-diff-f">
<div class="k-diff-l">@if (same.labelCode) { <code>{{ same.label }}</code> } @else { {{ same.label }} }</div>
<div class="k-diff-v"><span class="k-diff-was">{{ same.value }}</span></div>
</div>
}
</div>
</ng-template>

17
ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts

@ -41,7 +41,7 @@ const intro: { owner: AiAssistantButtonComponent | null } = {owner: null};
@Component({ @Component({
selector: 'tb-ai-assistant-button', selector: 'tb-ai-assistant-button',
template: ` template: `
@if (available && !panelService.open() && !panelService.suppressed()) { @if (available() && !panelService.open() && !panelService.suppressed()) {
@let status = cue(); @let status = cue();
<button #aiButton tb-ai-mark class="tb-ai-assistant-button" [cue]="markCue()" <button #aiButton tb-ai-mark class="tb-ai-assistant-button" [cue]="markCue()"
[working]="status?.level === 'running'" [glow]="introOpen()" [working]="status?.level === 'running'" [glow]="introOpen()"
@ -76,7 +76,7 @@ export class AiAssistantButtonComponent {
private readonly authState = getCurrentAuthState(this.store); private readonly authState = getCurrentAuthState(this.store);
readonly available = inject(UserPermissionsService).isAiAvailable(); readonly available = inject(UserPermissionsService).aiAvailable;
private dialog = inject(MatDialog); private dialog = inject(MatDialog);
@ -136,7 +136,7 @@ export class AiAssistantButtonComponent {
return level === 'needs' || level === 'error' ? level : null; 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() private introWanted = computed(() => this.available() && this.welcomeSeen() && !this.tourService.active() && !this.introSeen() && this.cue()?.level !== 'running' && !this.panelService.open()
&& !this.panelService.suppressed() && !!this.buttonRef()); && !this.panelService.suppressed() && !!this.buttonRef());
private introEffect = effect(() => { private introEffect = effect(() => {
@ -151,10 +151,13 @@ export class AiAssistantButtonComponent {
}); });
}); });
constructor() { private statusWatch = effect(() => {
if (this.available) { if (this.available()) {
this.chats.watchStatus(); untracked(() => this.chats.watchStatus());
} }
});
constructor() {
inject(Router).events.pipe( inject(Router).events.pipe(
filter(event => event instanceof NavigationStart || event instanceof NavigationEnd), filter(event => event instanceof NavigationStart || event instanceof NavigationEnd),
takeUntilDestroyed() takeUntilDestroyed()
@ -167,7 +170,7 @@ export class AiAssistantButtonComponent {
} }
}); });
const removeOpener = inject(AiSlashService).setOpener({ const removeOpener = inject(AiSlashService).setOpener({
canOpen: () => this.available && !this.panelService.open() && !this.panelService.suppressed(), canOpen: () => this.available() && !this.panelService.open() && !this.panelService.suppressed(),
open: () => this.openChat() open: () => this.openChat()
}); });
inject(DestroyRef).onDestroy(() => { inject(DestroyRef).onDestroy(() => {

73
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts

@ -99,43 +99,50 @@ export class AiAssistantPanelComponent {
onCleanup(() => document.documentElement.classList.remove('tb-ai-docked')); onCleanup(() => document.documentElement.classList.remove('tb-ai-docked'));
}); });
private wasOpen = false;
private openEffect = effect(() => { private openEffect = effect(() => {
if (this.panelService.open()) { const open = this.panelService.open();
untracked(() => { const composed = this.panelService.composed();
if (this.panelService.composesFresh()) { untracked(() => {
this.chatId.set(undefined); const opened = open && !this.wasOpen;
this.chats.load().subscribe(); this.wasOpen = open;
return; if (!open) {
} return;
const carried = this.panelService.hasCarriedChat(); }
if (!carried) { if (composed) {
this.dropChatFromOtherContext(); this.startComposed(this.panelService.takeComposed(), opened);
} } else if (opened) {
this.chats.load().subscribe(() => { this.restoreChat();
if (carried) { }
const chatId = this.panelService.takeCarriedChat(); });
if (chatId && this.chats.find(chatId)) {
this.chatId.set(chatId);
return;
}
}
this.selectLastChat();
});
});
}
}); });
private composeEffect = effect(() => { private startComposed(text: string, opened: boolean): void {
if (this.panelService.composed() && this.panelService.open()) { this.chat?.keepDraftForCompose();
untracked(() => { this.chatId.set(undefined);
const composed = this.panelService.takeComposed(); if (opened) {
if (composed.fresh) { this.chats.load().subscribe();
this.chatId.set(undefined);
}
setTimeout(() => this.chat?.composeText(composed.text), AiAssistantPanelComponent.COMPOSE_DELAY_MS);
});
} }
}); setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS);
}
private restoreChat(): void {
const carried = this.panelService.hasCarriedChat();
if (!carried) {
this.dropChatFromOtherContext();
}
this.chats.load().subscribe(() => {
if (carried) {
const chatId = this.panelService.takeCarriedChat();
if (chatId && this.chats.find(chatId)) {
this.chatId.set(chatId);
return;
}
}
this.selectLastChat();
});
}
private contextSwitchEffect = effect(() => { private contextSwitchEffect = effect(() => {
const key = this.panelService.contextKey(); const key = this.panelService.contextKey();

5
ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts

@ -0,0 +1,5 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// The chat head is narrow below this width (px); the CSS breakpoints of the AI chat are in _ai-breakpoints.scss.
export const AI_NARROW_HEAD_WIDTH = 500;

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

@ -177,7 +177,7 @@
<p class="lead">{{ msg.lead }}</p> <p class="lead">{{ msg.lead }}</p>
} }
@for (key of [decorationKey(msg)]; track key) { @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> <tb-markdown usePlainMarkdown sanitizeHtml [highlight]="false" [additionalStyles]="additionalStyles" [data]="parseResult(msg.done !== undefined ? withoutDoneMark(msg.content) : msg.content)" (ready)="decorateCode(answer, msg)"></tb-markdown>
} }
@let madeHere = made[$index] ?? []; @let madeHere = made[$index] ?? [];
@for (shown of records[$index] ?? []; track $index) { @for (shown of records[$index] ?? []; track $index) {

3
ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss

@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
@use './ai-icon-button' as *; @use './ai-icon-button' as *;
@use './ai-breakpoints' as *;
:host { :host {
display: contents; display: contents;
} }
@ -143,7 +144,7 @@
@include ai-icon-button; @include ai-icon-button;
} }
@container k-head (max-width: 399px) { @container k-head (max-width: #{$ai-head-status-hidden-below - 1px}) {
.ai-chat-status > span:last-child { .ai-chat-status > span:last-child {
display: none; display: none;
} }

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

@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { escapeHtml } from '@core/utils';
import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip';
import { AI_NARROW_HEAD_WIDTH } from '@home/components/ai/ai-breakpoints';
import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models';
import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models'; import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models';
import { getDefaultTimezone } from '@shared/models/time/time.models'; import { getDefaultTimezone } from '@shared/models/time/time.models';
@ -124,8 +126,6 @@ export class AiChatComponent implements OnInit, OnDestroy {
private static readonly NEW_CHAT_TITLE = 'New chat'; private static readonly NEW_CHAT_TITLE = 'New chat';
private static readonly NARROW_HEAD = 500;
@ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent;
@ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent;
@ -530,9 +530,18 @@ export class AiChatComponent implements OnInit, OnDestroy {
untracked(() => this.countNewTurns()); untracked(() => this.countNewTurns());
}); });
private readonly keptDrafts = new Map<string | null, string>();
private composing = false;
private chatIdEffect = effect(() => { private chatIdEffect = effect(() => {
const chatId = this.chatId(); const chatId = this.chatId() ?? null;
untracked(() => { untracked(() => {
const draft = this.keptDrafts.get(chatId);
if (draft !== undefined && !(chatId === null && this.composing)) {
this.keptDrafts.delete(chatId);
setTimeout(() => this.promptInput?.setValue(draft));
}
if (this.fileChat !== chatId) { if (this.fileChat !== chatId) {
this.shownFile.set(null); this.shownFile.set(null);
this.fileOpen.set(false); this.fileOpen.set(false);
@ -578,7 +587,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
if (typeof ResizeObserver !== 'undefined') { if (typeof ResizeObserver !== 'undefined') {
const head = new ResizeObserver(() => { const head = new ResizeObserver(() => {
const width = this.hostElement.querySelector('.ai-chat-head')?.clientWidth ?? 0; const width = this.hostElement.querySelector('.ai-chat-head')?.clientWidth ?? 0;
this.headNarrow.set(width > 0 && width < AiChatComponent.NARROW_HEAD); this.headNarrow.set(width > 0 && width < AI_NARROW_HEAD_WIDTH);
}); });
head.observe(this.hostElement); head.observe(this.hostElement);
this.destroyRef.onDestroy(() => head.disconnect()); this.destroyRef.onDestroy(() => head.disconnect());
@ -635,7 +644,19 @@ export class AiChatComponent implements OnInit, OnDestroy {
setTimeout(() => this.focus()); setTimeout(() => this.focus());
} }
keepDraftForCompose(): void {
const chatId = this.chatId() ?? null;
const draft = this.promptInput?.message.value ?? '';
if (draft.trim()) {
this.keptDrafts.set(chatId, draft);
} else {
this.keptDrafts.delete(chatId);
}
this.composing = true;
}
composeText(text: string): void { composeText(text: string): void {
this.composing = false;
this.promptInput?.setValue(text); this.promptInput?.setValue(text);
setTimeout(() => this.focus()); setTimeout(() => this.focus());
} }
@ -676,11 +697,11 @@ export class AiChatComponent implements OnInit, OnDestroy {
if (chatId) { if (chatId) {
AiChatComponent.store(AiChatComponent.UNLISTED_KEY + chatId, JSON.stringify([...next])); AiChatComponent.store(AiChatComponent.UNLISTED_KEY + chatId, JSON.stringify([...next]));
} }
this.showToast(this.translate.instant('ai-assistant.file.unlisted', {name: file.name}), 'success'); this.showToast(this.translate.instant('ai-assistant.file.unlisted', {name: escapeHtml(file.name)}), 'success');
} }
onFileDiscarded(file: AiFile): void { onFileDiscarded(file: AiFile): void {
this.showToast(this.translate.instant('ai-assistant.file.discarded', {name: file.name}), 'success'); this.showToast(this.translate.instant('ai-assistant.file.discarded', {name: escapeHtml(file.name)}), 'success');
} }
private saveFile(content: string): Promise<boolean> { private saveFile(content: string): Promise<boolean> {

8
ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts

@ -22,13 +22,13 @@ import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/a
AiFadeInImageDirective, AiFadeInImageDirective,
AiSpinComponent, AiSpinComponent,
AiSevMarkComponent, AiSevMarkComponent,
AiNoTelemetryModalComponent AiNoTelemetryModalComponent,
AiTooltipChainDirective,
AiTipIfCutDirective
], ],
imports: [ imports: [
CommonModule, CommonModule,
SharedModule, SharedModule
AiTooltipChainDirective,
AiTipIfCutDirective
], ],
exports: [ exports: [
AiAssistantButtonComponent, AiAssistantButtonComponent,

2
ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts

@ -42,7 +42,7 @@ const SAVED_MS = 1600;
</div> </div>
} @else if (file().markdown) { } @else if (file().markdown) {
<div class="file-md art-page agent"> <div class="file-md art-page agent">
<tb-markdown usePlainMarkdown [data]="file().content" [additionalStyles]="markdownStyles"></tb-markdown> <tb-markdown usePlainMarkdown sanitizeHtml [data]="file().content" [additionalStyles]="markdownStyles"></tb-markdown>
</div> </div>
} @else if (file().image) { } @else if (file().image) {
<div class="file-svg"> <div class="file-svg">

12
ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html

@ -23,7 +23,7 @@
} }
<div class="k-body"> <div class="k-body">
@if (handOver().text) { @if (handOver().text) {
<tb-markdown usePlainMarkdown [highlight]="false" [data]="md(handOver().text)" (ready)="decorate()"></tb-markdown> <tb-markdown usePlainMarkdown sanitizeHtml [highlight]="false" [data]="md(handOver().text)" (ready)="decorate()"></tb-markdown>
} }
@if (handOver().choice; as choice) { @if (handOver().choice; as choice) {
<div class="k-choice-panel"> <div class="k-choice-panel">
@ -42,7 +42,7 @@
</span> </span>
</div> </div>
@if (choiceText()) { @if (choiceText()) {
<div class="k-choice-body"><tb-markdown usePlainMarkdown [highlight]="false" [data]="md(choiceText())" (ready)="decorate()"></tb-markdown></div> <div class="k-choice-body"><tb-markdown usePlainMarkdown sanitizeHtml [highlight]="false" [data]="md(choiceText())" (ready)="decorate()"></tb-markdown></div>
} }
</div> </div>
} }
@ -90,7 +90,7 @@
} }
</div> </div>
@if (step.markdown) { @if (step.markdown) {
<tb-markdown usePlainMarkdown [highlight]="false" [data]="md(step.markdown)" (ready)="decorate()"></tb-markdown> <tb-markdown usePlainMarkdown sanitizeHtml [highlight]="false" [data]="md(step.markdown)" (ready)="decorate()"></tb-markdown>
} }
</div> </div>
} }
@ -108,9 +108,9 @@
} }
@if (stopped()) { @if (stopped()) {
<div class="k-quiet"> <div class="k-quiet">
<div class="k-wait stopped" role="status"> <div class="k-wait" [class.stopped]="!undecoded()" [class.warn]="undecoded()" role="status">
<mat-icon class="tb-mat-18" aria-hidden="true">stop_circle</mat-icon> <mat-icon class="tb-mat-18" aria-hidden="true">{{ undecoded() ? 'schedule' : 'stop_circle' }}</mat-icon>
<span class="k-wait-t">{{ 'ai-assistant.hand-over.stopped-at' | translate: {time: stoppedAt()} }}</span> <span class="k-wait-t">{{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.stopped-at') | translate: {time: stoppedAt()} }}</span>
@if (canListenAgain()) { @if (canListenAgain()) {
<span class="k-wait-tools"> <span class="k-wait-tools">
<button mat-button type="button" (click)="listenAgain.emit()"> <button mat-button type="button" (click)="listenAgain.emit()">

2
ui-ngx/src/app/modules/home/components/ai/ai-text.ts

@ -21,7 +21,7 @@ const CHAT_NAME_MAX = 44;
const CHAT_NAME_MIN_CUT = 20; const CHAT_NAME_MIN_CUT = 20;
export function aiChatNameOf(prompt: string): string { export function aiChatNameOf(prompt: string): string {
const first = prompt.replace(/[*_`#>]/g, '').trim().split(/[.:\n]/)[0].trim(); const first = prompt.replace(/[*`#>]|(?<![^\s])_+|_+(?![^\s])/g, '').trim().split(/[.!?](?:\s|$)|:\s|\n/)[0].trim();
if (first.length <= CHAT_NAME_MAX) { if (first.length <= CHAT_NAME_MAX) {
return first; return first;
} }

44
ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { Directive, ElementRef, HostListener, inject, Provider } from '@angular/core'; import { Directive, ElementRef, inject, Provider } from '@angular/core';
import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltip, MatTooltipDefaultOptions } from '@angular/material/tooltip'; import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltip, MatTooltipDefaultOptions } from '@angular/material/tooltip';
export const AI_TOOLTIP_OPTIONS: MatTooltipDefaultOptions = { export const AI_TOOLTIP_OPTIONS: MatTooltipDefaultOptions = {
@ -17,54 +17,66 @@ const NEXT_AT_ONCE_MS = 400;
let lastTipAt = 0; let lastTipAt = 0;
function focusedByKeyboard(element: HTMLElement): boolean {
return element.matches(':focus-visible');
}
@Directive({ @Directive({
selector: '[matTooltip]', selector: '[matTooltip]',
standalone: true standalone: false,
host: {
'(mouseenter)': 'onEnter()',
'(mouseleave)': 'onLeave()',
'(focus)': 'onFocus()'
}
}) })
export class AiTooltipChainDirective { export class AiTooltipChainDirective {
private tooltip = inject(MatTooltip, {self: true}); private tooltip = inject(MatTooltip, {self: true});
private host = inject<ElementRef<HTMLElement>>(ElementRef); private host = inject<ElementRef<HTMLElement>>(ElementRef);
private inChat = inject(MAT_TOOLTIP_DEFAULT_OPTIONS, {optional: true}) === AI_TOOLTIP_OPTIONS;
@HostListener('mouseenter')
onEnter(): void { onEnter(): void {
if (this.inChat()) { if (this.inChat) {
this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay; this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay;
} }
} }
@HostListener('mouseleave')
onLeave(): void { onLeave(): void {
if (this.inChat() && this.tooltip._isTooltipVisible()) { if (this.inChat && this.tooltip._isTooltipVisible()) {
lastTipAt = Date.now(); lastTipAt = Date.now();
} }
} }
@HostListener('focus')
onFocus(): void { onFocus(): void {
if (this.inChat()) { if (this.inChat && !this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) {
this.tooltip.showDelay = this.host.nativeElement.matches(':focus-visible') ? 0 : AI_TOOLTIP_OPTIONS.showDelay; this.tooltip.show(0);
} }
} }
private inChat(): boolean {
return (this.tooltip.tooltipClass as string | string[]) === AI_TOOLTIP_OPTIONS.tooltipClass;
}
} }
@Directive({ @Directive({
selector: '[aiTipIfCut]', selector: '[aiTipIfCut]',
standalone: true standalone: false,
host: {
'(mouseenter)': 'check()',
'(focus)': 'onFocus()'
}
}) })
export class AiTipIfCutDirective { export class AiTipIfCutDirective {
private tooltip = inject(MatTooltip, {self: true}); private tooltip = inject(MatTooltip, {self: true});
private host = inject<ElementRef<HTMLElement>>(ElementRef); private host = inject<ElementRef<HTMLElement>>(ElementRef);
@HostListener('mouseenter')
@HostListener('focus')
check(): void { check(): void {
const element = this.host.nativeElement.querySelector<HTMLElement>('.tb-ai-cut') ?? this.host.nativeElement; const element = this.host.nativeElement.querySelector<HTMLElement>('.tb-ai-cut') ?? this.host.nativeElement;
this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1; this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1;
} }
onFocus(): void {
this.check();
if (!this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) {
this.tooltip.show(0);
}
}
} }

5
ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts

@ -352,9 +352,8 @@ export class AiWidgetCheckService {
} }
private plain(html: string): string { private plain(html: string): string {
const div = document.createElement('div'); const body = new DOMParser().parseFromString(html, 'text/html').body;
div.innerHTML = html; return (body.textContent || '').replace(/\s+/g, ' ').trim();
return (div.textContent || '').replace(/\s+/g, ' ').trim();
} }
private clip(text: string): string { private clip(text: string): string {

2
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html

@ -25,7 +25,7 @@
@if (dashboard.overview) { @if (dashboard.overview) {
<p class="sol-dash-lead">{{ dashboard.overview }}</p> <p class="sol-dash-lead">{{ dashboard.overview }}</p>
} }
<tb-markdown class="sol-dash-doc" usePlainMarkdown [additionalStyles]="markdownStyles" [data]="details(dashboard)"></tb-markdown> <tb-markdown class="sol-dash-doc" usePlainMarkdown sanitizeHtml [additionalStyles]="markdownStyles" [data]="details(dashboard)"></tb-markdown>
</section> </section>
} @empty { } @empty {
<p class="sol-empty">{{ 'solution-creator.pane.no-dashboards' | translate }}</p> <p class="sol-empty">{{ 'solution-creator.pane.no-dashboards' | translate }}</p>

15
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { roleOperations } from './solution-overview.component';
import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { AuthService } from '@core/auth/auth.service'; import { AuthService } from '@core/auth/auth.service';
@ -69,7 +70,6 @@ const GROUPS: SectionSpec[] = [
{id: 'chains', types: [EntityType.RULE_CHAIN], title: 'entity.type-rulechains', link: null} {id: 'chains', types: [EntityType.RULE_CHAIN], title: 'entity.type-rulechains', link: null}
]; ];
const OPERATIONS: Record<string, string> = {C: 'create', R: 'read', U: 'update', D: 'delete'};
const SECTIONS: EntityType[] = GROUPS.flatMap(group => group.types); const SECTIONS: EntityType[] = GROUPS.flatMap(group => group.types);
@ -239,8 +239,9 @@ export class SolutionInstalledComponent {
return {kindLabel: this.translate.instant('entity.type-asset')}; return {kindLabel: this.translate.instant('entity.type-asset')};
case EntityType.ROLE: { case EntityType.ROLE: {
const permissions = solution?.solutionDescriptor?.iam?.find(role => role.name === name)?.permissions ?? ''; const permissions = solution?.solutionDescriptor?.iam?.find(role => role.name === name)?.permissions ?? '';
return {ops: permissions.toUpperCase().split('').filter(letter => OPERATIONS[letter]) const operations = roleOperations(permissions);
.map(letter => this.translate.instant('solution-creator.pane.op-' + OPERATIONS[letter]))}; return {ops: operations.length ? [this.translate.instant('solution-creator.pane.all-resources'),
...operations.map(operation => this.translate.instant('solution-creator.pane.op-' + operation))] : []};
} }
case EntityType.ALARM: case EntityType.ALARM:
return {severities: data.severities?.length ? data.severities return {severities: data.severities?.length ? data.severities
@ -303,10 +304,6 @@ export class SolutionInstalledComponent {
return (severity ?? '').toLowerCase(); return (severity ?? '').toLowerCase();
} }
dashboardUser(row: AggregatedEntityResult): string {
return this.userName(row.primary?.additionalData?.userId);
}
canViewAs(row: AggregatedEntityResult): boolean { canViewAs(row: AggregatedEntityResult): boolean {
return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR; return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR;
} }
@ -319,10 +316,6 @@ export class SolutionInstalledComponent {
this.authService.loginAsUser(userId).subscribe(() => {}); this.authService.loginAsUser(userId).subscribe(() => {});
} }
private userName(userId: string | undefined): string {
return userId ? this.findUser(userId)?.additionalData?.name ?? '' : '';
}
private findUser(userId: string): EntityResult | undefined { private findUser(userId: string): EntityResult | undefined {
return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId); return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId);
} }

3
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html

@ -130,6 +130,9 @@
</td> </td>
<td> <td>
<div class="sol-chips"> <div class="sol-chips">
@if (operations(iam).length) {
<span class="sol-op">{{ 'solution-creator.pane.all-resources' | translate }}</span>
}
@for (operation of operations(iam); track operation) { @for (operation of operations(iam); track operation) {
<span class="sol-op">{{ ('solution-creator.pane.op-' + operation) | translate }}</span> <span class="sol-op">{{ ('solution-creator.pane.op-' + operation) | translate }}</span>
} @empty { } @empty {

7
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts

@ -38,6 +38,11 @@ interface Section {
const OPERATIONS: Record<string, string> = {C: 'create', R: 'read', U: 'update', D: 'delete'}; const OPERATIONS: Record<string, string> = {C: 'create', R: 'read', U: 'update', D: 'delete'};
export function roleOperations(permissions: string | undefined): string[] {
const operations = (permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]);
return operations.length === Object.keys(OPERATIONS).length ? ['all'] : operations;
}
@Component({ @Component({
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'tb-solution-overview', selector: 'tb-solution-overview',
@ -177,7 +182,7 @@ export class SolutionOverviewComponent implements OnChanges, AfterViewInit, OnDe
} }
operations(iam: SolutionDescriptorIam): string[] { operations(iam: SolutionDescriptorIam): string[] {
return (iam.permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]); return roleOperations(iam.permissions);
} }
alarmKey(alarm: SolutionDescriptorAlarm): string { alarmKey(alarm: SolutionDescriptorAlarm): string {

2
ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html

@ -13,7 +13,7 @@
</mat-toolbar> </mat-toolbar>
<div mat-dialog-content class="relative flex flex-col gap-2"> <div mat-dialog-content class="relative flex flex-col gap-2">
<div class="text-justify"> <div class="text-justify">
<tb-markdown usePlainMarkdown [data]=solution.data.solutionDescription></tb-markdown> <tb-markdown usePlainMarkdown sanitizeHtml [data]=solution.data.solutionDescription></tb-markdown>
</div> </div>
@let dashboardEntries = aggregatedFor(EntityType.DASHBOARD); @let dashboardEntries = aggregatedFor(EntityType.DASHBOARD);
@if (dashboardEntries.length > 0) { @if (dashboardEntries.length > 0) {

23
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts

@ -1,5 +1,10 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { escapeHtml, escapeHtmlAttr } from '@core/utils';
export { escapeHtml, escapeHtmlAttr };
export const ITEM_LINK_PLACEHOLDER_REGEX = export const ITEM_LINK_PLACEHOLDER_REGEX =
/\$\{item-link:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})}/g; /\$\{item-link:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})}/g;
@ -44,22 +49,6 @@ function buildDocLinkButton(url: string, text: string, icon: string): string {
`<tb-icon matButtonIcon>${icon}</tb-icon><span>${safeText}</span></a>`; `<tb-icon matButtonIcon>${icon}</tb-icon><span>${safeText}</span></a>`;
} }
export function escapeHtml(value: string): string {
return value.replace(/[&<>]/g, ch => ch === '&' ? '&amp;' : ch === '<' ? '&lt;' : '&gt;');
}
export function escapeHtmlAttr(value: string): string {
return value.replace(/[&<>"']/g, ch => {
switch (ch) {
case '&': return '&amp;';
case '<': return '&lt;';
case '>': return '&gt;';
case '"': return '&quot;';
default: return '&#39;';
}
});
}
// Inline-only tags + a small attribute whitelist that are safe to keep // Inline-only tags + a small attribute whitelist that are safe to keep
// in caption strings (or other small bits of user-authored HTML inside // in caption strings (or other small bits of user-authored HTML inside
// generated markdown). Anything else is dropped — disallowed tags are // generated markdown). Anything else is dropped — disallowed tags are

4
ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts

@ -16,7 +16,7 @@ import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-it
import { PageLink } from '@shared/models/page/page-link'; import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { UserPermissionsService } from '@core/http/user-permissions.service'; import { UserPermissionsService } from '@core/http/user-permissions.service';
import { Operation, Resource } from '@shared/models/security.models'; import { Operation } from '@shared/models/security.models';
const WIDGET_CARD_COUNT = 3; const WIDGET_CARD_COUNT = 3;
@ -51,7 +51,7 @@ export class IotHubWidgetComponent extends PageComponent implements OnInit {
ngOnInit() { ngOnInit() {
this.ctx.overflowVisible = true; this.ctx.overflowVisible = true;
this.hasIotHubAccess = [Authority.TENANT_ADMIN].includes(this.authUser.authority) && this.hasIotHubAccess = [Authority.TENANT_ADMIN].includes(this.authUser.authority) &&
this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); this.userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
if (this.hasIotHubAccess) { if (this.hasIotHubAccess) {
this.load(); this.load();
} }

4
ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts

@ -13,7 +13,7 @@ import { UsageInfo } from '@shared/models/usage.models';
import { UsageInfoService } from '@core/http/usage-info.service'; import { UsageInfoService } from '@core/http/usage-info.service';
import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; import { ShortNumberPipe } from '@shared/pipe/short-number.pipe';
import { UserPermissionsService } from '@core/http/user-permissions.service'; import { UserPermissionsService } from '@core/http/user-permissions.service';
import { Operation, Resource } from '@shared/models/security.models'; import { Operation } from '@shared/models/security.models';
@Component({ @Component({
selector: 'tb-usage-info-widget', selector: 'tb-usage-info-widget',
@ -48,7 +48,7 @@ export class UsageInfoWidgetComponent extends PageComponent implements OnInit, O
ngOnInit() { ngOnInit() {
this.hasUsageInfoAccess = this.authUser.authority === Authority.TENANT_ADMIN && this.hasUsageInfoAccess = this.authUser.authority === Authority.TENANT_ADMIN &&
this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.READ); this.userPermissionsService.hasGenericPermissionExceptAi(Operation.READ);
if (this.hasUsageInfoAccess) { if (this.hasUsageInfoAccess) {
this.usageInfoService.getUsageInfo().subscribe( this.usageInfoService.getUsageInfo().subscribe(
(usageInfo) => { (usageInfo) => {

2
ui-ngx/src/app/modules/home/home.component.html

@ -118,7 +118,7 @@
</div> </div>
</div> </div>
</div> </div>
@if (aiAvailable) { @if (aiAvailable()) {
<ng-container #aiPanelHost></ng-container> <ng-container #aiPanelHost></ng-container>
} }
</mat-sidenav-content> </mat-sidenav-content>

16
ui-ngx/src/app/modules/home/home.component.ts

@ -21,6 +21,7 @@ import { FormBuilder } from '@angular/forms';
import { WhiteLabelingService } from '@core/http/white-labeling.service'; import { WhiteLabelingService } from '@core/http/white-labeling.service';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { TourService } from '@core/services/tour.service'; import { TourService } from '@core/services/tour.service';
import { UserPermissionsService } from '@core/http/user-permissions.service';
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service';
import { ActionPreferencesPutUserSettings } from '@core/auth/auth.actions'; import { ActionPreferencesPutUserSettings } from '@core/auth/auth.actions';
import { HomeService } from '@core/services/home.service'; import { HomeService } from '@core/services/home.service';
@ -74,17 +75,24 @@ export class HomeComponent extends PageComponent implements AfterViewInit, OnIni
private tourService = inject(TourService); private tourService = inject(TourService);
readonly aiAvailable = this.tourService.aiAvailable(); readonly aiAvailable = inject(UserPermissionsService).aiAvailable;
readonly aiPanelLoaded = signal(false); readonly aiPanelLoaded = signal(false);
private injector = inject(Injector); private injector = inject(Injector);
@ViewChild('aiPanelHost', {read: ViewContainerRef}) set aiPanelHost(host: ViewContainerRef) { private panelHost: ViewContainerRef | undefined;
if (host && !this.aiPanelLoaded()) {
@ViewChild('aiPanelHost', {read: ViewContainerRef}) set aiPanelHost(host: ViewContainerRef | undefined) {
this.panelHost = host;
if (!host) {
this.aiPanelLoaded.set(false);
return;
}
if (!this.aiPanelLoaded()) {
Promise.all([import('@home/components/ai/ai.module'), import('@home/components/ai/ai-assistant-panel.component')]) Promise.all([import('@home/components/ai/ai.module'), import('@home/components/ai/ai-assistant-panel.component')])
.then(([{AiModule}, {AiAssistantPanelComponent}]) => { .then(([{AiModule}, {AiAssistantPanelComponent}]) => {
if (!this.aiPanelLoaded()) { if (this.panelHost === host && !this.aiPanelLoaded()) {
host.createComponent(AiAssistantPanelComponent, {ngModuleRef: createNgModule(AiModule, this.injector)}); host.createComponent(AiAssistantPanelComponent, {ngModuleRef: createNgModule(AiModule, this.injector)});
this.aiPanelLoaded.set(true); this.aiPanelLoaded.set(true);
} }

6
ui-ngx/src/app/modules/home/menu/menu-link.component.ts

@ -4,6 +4,7 @@
import { ChangeDetectionStrategy, Component, computed, inject, Input, OnInit, signal } from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, inject, Input, OnInit, signal } from '@angular/core';
import { MenuId, MenuSection } from '@core/services/menu.models'; import { MenuId, MenuSection } from '@core/services/menu.models';
import { AiChatsService } from '@core/services/ai-chats.service'; import { AiChatsService } from '@core/services/ai-chats.service';
import { AiSolutionsService } from '@core/services/ai-solutions.service';
import { coerceBoolean } from '@shared/decorators/coercion'; import { coerceBoolean } from '@shared/decorators/coercion';
@Component({ @Component({
@ -27,13 +28,16 @@ export class MenuLinkComponent implements OnInit {
private countsChats = signal(false); private countsChats = signal(false);
private solutions = inject(AiSolutionsService);
readonly needYou = computed(() => this.countsChats() readonly needYou = computed(() => this.countsChats()
? this.chats.statusChats().filter(chat => this.chats.needsAttention(chat)).length : 0); ? this.chats.statusChats().filter(chat => this.chats.needsAttention(chat)).length + this.solutions.attention().length : 0);
ngOnInit(): void { ngOnInit(): void {
if (this.section?.id === MenuId.ai_assistant) { if (this.section?.id === MenuId.ai_assistant) {
this.countsChats.set(true); this.countsChats.set(true);
this.chats.watchStatus(); this.chats.watchStatus();
this.solutions.ensureLoaded();
} }
} }

14
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts

@ -217,6 +217,18 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
} }
}); });
private composeEffect = effect(() => {
const composed = this.panelService.composed();
if (composed && this.ready() && this.panelService.suppressed()) {
untracked(() => {
const text = this.panelService.takeComposed();
this.chat?.keepDraftForCompose();
this.newChat();
setTimeout(() => this.chat?.composeText(text));
});
}
});
private listEdgesEffect = effect(() => { private listEdgesEffect = effect(() => {
this.groups(); this.groups();
setTimeout(() => this.listEdges()); setTimeout(() => this.listEdges());
@ -267,7 +279,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
next: ([, chats]) => { next: ([, chats]) => {
const params = this.route.snapshot.queryParamMap; const params = this.route.snapshot.queryParamMap;
const handOff = this.panelService.takeHandOff(); const handOff = this.panelService.takeHandOff();
const first = !handOff && !params.get('chatId') && !params.get('solutionId') && !chats.length; const first = !handOff && !this.panelService.composed() && !params.get('chatId') && !params.get('solutionId') && !chats.length;
this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats, first || params.get('getStarted') === 'true', this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats, first || params.get('getStarted') === 'true',
params.get('cli') === 'true'); params.get('cli') === 'true');
this.ready.set(true); this.ready.set(true);

64
ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts

@ -4,13 +4,24 @@ import { ChangeDetectionStrategy, Component, computed, effect, inject, signal }
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { interval } from 'rxjs'; import { interval } from 'rxjs';
import { ChatInfo } from '@shared/models/ai-chat.models'; import { ChatLevel } from '@shared/models/ai-chat.models';
import { homeAgo, homeElapsed } from '@home/pages/home-page/home-list.models'; import { homeAgo, homeElapsed } from '@home/pages/home-page/home-list.models';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { getCurrentAuthUser } from '@core/auth/auth.selectors';
import { readStored, writeStored } from '@core/local-storage/stored'; import { readStored, writeStored } from '@core/local-storage/stored';
import { AiChatsService } from '@core/services/ai-chats.service'; import { AiChatsService } from '@core/services/ai-chats.service';
import { AiSolutionsService } from '@core/services/ai-solutions.service';
interface WaitingItem {
id: string;
title: string;
level: ChatLevel;
tip: string;
updatedTime?: number;
recency: number;
queryParams: {chatId?: string; solutionId?: string};
}
const SHOWN = 2; const SHOWN = 2;
@ -19,7 +30,7 @@ const TICK_MS = 60_000;
@Component({ @Component({
selector: 'tb-waiting-ai-chats-home', selector: 'tb-waiting-ai-chats-home',
template: ` template: `
@if (!chats.statusResolved()) { @if (!resolved()) {
@if (reserved) { @if (reserved) {
<div class="tb-ai-attn-block reserve" aria-hidden="true"> <div class="tb-ai-attn-block reserve" aria-hidden="true">
<div class="tb-ai-attn-h">{{ 'home.ai.waiting' | translate }}</div> <div class="tb-ai-attn-h">{{ 'home.ai.waiting' | translate }}</div>
@ -34,13 +45,13 @@ const TICK_MS = 60_000;
<div class="tb-ai-attn-block" [class.appear]="!reserved"> <div class="tb-ai-attn-block" [class.appear]="!reserved">
<div class="tb-ai-attn-h" id="tb-ai-attn-h">{{ 'home.ai.waiting' | translate }}</div> <div class="tb-ai-attn-h" id="tb-ai-attn-h">{{ 'home.ai.waiting' | translate }}</div>
<div class="tb-ai-attn" role="group" aria-labelledby="tb-ai-attn-h"> <div class="tb-ai-attn" role="group" aria-labelledby="tb-ai-attn-h">
@for (chat of shown(); track chat.id) { @for (item of shown(); track item.id) {
@let elapsed = elapsedOf(chat); @let elapsed = elapsedOf(item);
<a class="tb-chat-pill" routerLink="/ai-assistant" [queryParams]="{chatId: chat.id}" <a class="tb-chat-pill" routerLink="/ai-assistant" [queryParams]="item.queryParams"
[matTooltip]="elapsed ? ('home.ai.waiting-tip' | translate: {tip: chats.tipOf(chat), ago: agoOf(chat)}) : chats.tipOf(chat)" [matTooltip]="elapsed ? ('home.ai.waiting-tip' | translate: {tip: item.tip, ago: agoOf(item)}) : item.tip"
matTooltipPosition="below"> matTooltipPosition="below">
<span class="tb-ai-status-mark" [class]="chats.levelOf(chat)" aria-hidden="true"></span> <span class="tb-ai-status-mark" [class]="item.level" aria-hidden="true"></span>
<span class="tb-chat-pill-t">{{ chat.title || ('ai-assistant.new-chat' | translate) }}</span> <span class="tb-chat-pill-t">{{ item.title }}</span>
@if (elapsed) { @if (elapsed) {
<span class="tb-chat-pill-m">{{ elapsed }}</span> <span class="tb-chat-pill-m">{{ elapsed }}</span>
} }
@ -62,8 +73,30 @@ export class WaitingAIChatsHomeComponent {
private readonly now = signal(Date.now()); private readonly now = signal(Date.now());
readonly waiting = computed(() => this.chats.statusChats().filter(chat => this.chats.needsAttention(chat)) private readonly solutions = inject(AiSolutionsService);
.sort((a, b) => (this.chats.levelOf(a) === 'error' ? 0 : 1) - (this.chats.levelOf(b) === 'error' ? 0 : 1)));
readonly resolved = computed(() => this.chats.statusResolved() && this.solutions.loaded());
readonly waiting = computed<WaitingItem[]>(() => [
...this.chats.statusChats().filter(chat => this.chats.needsAttention(chat)).map(chat => ({
id: chat.id,
title: chat.title || this.translate.instant('ai-assistant.new-chat'),
level: this.chats.levelOf(chat),
tip: this.chats.tipOf(chat),
updatedTime: chat.updatedTime,
recency: chat.updatedTime ?? chat.createdTime ?? 0,
queryParams: {chatId: chat.id}
})),
...this.solutions.attention().map(solution => ({
id: solution.id,
title: this.solutions.titleOf(solution),
level: this.solutions.levelOf(solution),
tip: this.solutions.tipOf(solution),
updatedTime: solution.updatedTime,
recency: solution.updatedTime ?? solution.createdTime ?? 0,
queryParams: {solutionId: solution.id}
}))
].sort((a, b) => (a.level === 'error' ? 0 : 1) - (b.level === 'error' ? 0 : 1) || b.recency - a.recency));
readonly shown = computed(() => this.waiting().slice(0, SHOWN)); readonly shown = computed(() => this.waiting().slice(0, SHOWN));
@ -75,20 +108,21 @@ export class WaitingAIChatsHomeComponent {
constructor() { constructor() {
this.chats.watchStatus(); this.chats.watchStatus();
this.solutions.ensureLoaded();
interval(TICK_MS).pipe(takeUntilDestroyed()).subscribe(() => this.now.set(Date.now())); interval(TICK_MS).pipe(takeUntilDestroyed()).subscribe(() => this.now.set(Date.now()));
effect(() => { effect(() => {
if (this.chats.statusResolved()) { if (this.resolved()) {
this.writeShown(this.shown().length); this.writeShown(this.shown().length);
} }
}); });
} }
elapsedOf(chat: ChatInfo): string | null { elapsedOf(item: WaitingItem): string | null {
return chat.updatedTime ? homeElapsed(this.translate, Math.max(0, this.now() - chat.updatedTime)) : null; return item.updatedTime ? homeElapsed(this.translate, Math.max(0, this.now() - item.updatedTime)) : null;
} }
agoOf(chat: ChatInfo): string { agoOf(item: WaitingItem): string {
return homeAgo(this.translate, Math.max(0, this.now() - chat.updatedTime)); return homeAgo(this.translate, Math.max(0, this.now() - item.updatedTime));
} }
private readShown(): number { private readShown(): number {

4
ui-ngx/src/app/modules/home/pages/home-page/home-permissions.service.ts

@ -81,7 +81,7 @@ export class HomePermissionsService {
} }
canUseIotHub(): boolean { canUseIotHub(): boolean {
return this.tenantAdmin && this.userPermissions.hasGenericPermission(Resource.ALL, Operation.ALL); return this.tenantAdmin && this.userPermissions.hasGenericPermissionExceptAi(Operation.ALL);
} }
canReadApiUsage(): boolean { canReadApiUsage(): boolean {
@ -90,7 +90,7 @@ export class HomePermissionsService {
} }
canReadUsageInfo(): boolean { canReadUsageInfo(): boolean {
return this.tenantAdmin && this.userPermissions.hasGenericPermission(Resource.ALL, Operation.READ); return this.tenantAdmin && this.userPermissions.hasGenericPermissionExceptAi(Operation.READ);
} }
canReadMobileAppSettings(): boolean { canReadMobileAppSettings(): boolean {

24
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-routing.module.ts

@ -12,7 +12,7 @@ import { TbIotHubInstalledItemsComponent } from './iot-hub-installed-items.compo
import { TbIotHubSearchPageComponent } from './iot-hub-search-page.component'; import { TbIotHubSearchPageComponent } from './iot-hub-search-page.component';
import { TbIotHubItemResolverComponent } from './iot-hub-item-resolver.component'; import { TbIotHubItemResolverComponent } from './iot-hub-item-resolver.component';
import { UserPermissionsService } from '@core/http/user-permissions.service'; import { UserPermissionsService } from '@core/http/user-permissions.service';
import { Operation, Resource } from '@shared/models/security.models'; import { Operation } from '@shared/models/security.models';
const routes: Routes = [ const routes: Routes = [
{ {
@ -31,7 +31,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.iot-hub' title: 'iot-hub.iot-hub'
} }
@ -42,7 +42,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'item.type-widget-plural', title: 'item.type-widget-plural',
itemType: 'WIDGET', itemType: 'WIDGET',
@ -55,7 +55,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'item.type-solution-template-plural', title: 'item.type-solution-template-plural',
itemType: 'SOLUTION_TEMPLATE', itemType: 'SOLUTION_TEMPLATE',
@ -68,7 +68,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'item.type-calculated-field-plural', title: 'item.type-calculated-field-plural',
itemType: 'CALCULATED_FIELD', itemType: 'CALCULATED_FIELD',
@ -91,7 +91,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'item.type-rule-chain-plural', title: 'item.type-rule-chain-plural',
itemType: 'RULE_CHAIN', itemType: 'RULE_CHAIN',
@ -104,7 +104,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.device-library', title: 'iot-hub.device-library',
itemType: 'DEVICE', itemType: 'DEVICE',
@ -117,7 +117,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.search-results', title: 'iot-hub.search-results',
breadcrumb: { breadcrumb: {
@ -132,7 +132,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.installed-items', title: 'iot-hub.installed-items',
breadcrumb: { breadcrumb: {
@ -147,7 +147,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.creator-profile', title: 'iot-hub.creator-profile',
breadcrumb: { breadcrumb: {
@ -170,7 +170,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.item-detail' title: 'iot-hub.item-detail'
} }
@ -181,7 +181,7 @@ const routes: Routes = [
data: { data: {
auth: [Authority.TENANT_ADMIN], auth: [Authority.TENANT_ADMIN],
canActivate: (userPermissionsService: UserPermissionsService): boolean => { canActivate: (userPermissionsService: UserPermissionsService): boolean => {
return userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); return userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL);
}, },
title: 'iot-hub.item-detail' title: 'iot-hub.item-detail'
} }

172
ui-ngx/src/app/shared/components/markdown-html-sanitize.ts

@ -0,0 +1,172 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import DOMPurify, { UponSanitizeAttributeHookEvent } from 'dompurify';
const ALLOWED_TAGS = [
'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del',
'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img',
'input', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'span', 'strong',
'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'u', 'ul', 'var', 'wbr'
];
const ALLOWED_ATTR = [
'abbr', 'align', 'alt', 'checked', 'cite', 'class', 'colspan', 'datetime', 'dir', 'disabled', 'headers', 'height', 'href',
'id', 'lang', 'ngnonbindable', 'onclick', 'open', 'rel', 'reversed', 'rowspan', 'scope', 'span', 'src', 'start', 'style', 'tabindex',
'target', 'title', 'type', 'valign', 'width'
];
const COPY_CODE_CLICK = /^markdownCopyCode\(\d+\)$/;
const COPY_CODE_ID = /^(codeWrapper|copyCodeId)\d+$/;
const SAFE_DATA_IMAGE = /^data:image\/(png|jpe?g|gif|webp|bmp);/i;
const ALLOWED_STYLE_PROPERTIES = new Set([
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-left', 'border-radius',
'border-right', 'border-spacing', 'border-style', 'border-top', 'border-width', 'color', 'display', 'font-family',
'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'list-style-type',
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'max-height', 'max-width', 'min-height',
'min-width', 'opacity', 'overflow', 'overflow-wrap', 'padding', 'padding-bottom', 'padding-left', 'padding-right',
'padding-top', 'table-layout', 'text-align', 'text-decoration', 'text-decoration-color', 'text-decoration-line',
'text-decoration-style', 'text-indent', 'text-transform', 'vertical-align', 'white-space', 'width', 'word-break'
]);
const ALLOWED_STYLE_FUNCTIONS = new Set(['rgb', 'rgba', 'hsl', 'hsla', 'calc', 'min', 'max', 'clamp']);
let purifier: ReturnType<typeof DOMPurify> | null = null;
/**
* Sanitizes HTML that is not trusted, such as AI content, for rendering with innerHTML. Only an allowlist of elements
* and attributes is kept: scripts, event handlers, SVG, forms and frames are dropped, and ids only stay on the copy-code
* markup of the markdown renderer. Images load only from this origin or from inline image data; an image from another
* host becomes a link to it, so nothing is fetched until the person opens it. Styles keep only text and box properties
* with plain values.
*/
export function sanitizeMarkdownHtml(html: string): string {
const body = getPurifier().sanitize(html, {
ALLOWED_TAGS,
ALLOWED_ATTR,
ALLOW_DATA_ATTR: true,
ALLOW_ARIA_ATTR: true,
RETURN_DOM: true
}) as HTMLElement;
postProcess(body);
return body.innerHTML;
}
function getPurifier(): ReturnType<typeof DOMPurify> {
if (!purifier) {
purifier = DOMPurify(window);
purifier.addHook('uponSanitizeAttribute', sanitizeAttribute);
}
return purifier;
}
function sanitizeAttribute(node: Element, data: UponSanitizeAttributeHookEvent): void {
const value = data.attrValue ?? '';
switch (data.attrName) {
case 'onclick':
if (COPY_CODE_CLICK.test(value.trim()) && node.classList.contains('code-wrapper')) {
data.forceKeepAttr = true;
} else {
data.keepAttr = false;
}
break;
case 'id':
if (!COPY_CODE_ID.test(value)) {
data.keepAttr = false;
}
break;
case 'style':
data.attrValue = sanitizeStyle(value);
if (!data.attrValue) {
data.keepAttr = false;
}
break;
}
}
function postProcess(root: HTMLElement): void {
root.querySelectorAll('img').forEach(img => {
if (!isSafeImageSource(img.getAttribute('src'))) {
replaceExternalImage(img);
}
});
root.querySelectorAll('button').forEach(button => {
if (!isCopyCodeButton(button)) {
button.replaceWith(...Array.from(button.childNodes));
}
});
root.querySelectorAll('input').forEach(input => {
if (input.getAttribute('type') !== 'checkbox' || !input.hasAttribute('disabled')) {
input.remove();
}
});
root.querySelectorAll('a[target]').forEach(link => link.setAttribute('rel', 'noopener noreferrer'));
}
function isSafeImageSource(src: string | null): boolean {
const value = src?.trim();
if (!value) {
return false;
}
if (value.toLowerCase().startsWith('data:')) {
return SAFE_DATA_IMAGE.test(value);
}
try {
return new URL(value, window.location.href).origin === window.location.origin;
} catch {
return false;
}
}
function replaceExternalImage(img: HTMLImageElement): void {
let href: URL | null = null;
try {
href = new URL(img.getAttribute('src')?.trim() ?? '', window.location.href);
} catch {
href = null;
}
if (!href || !/^https?:$/.test(href.protocol) || href.origin === window.location.origin) {
img.remove();
return;
}
const link = img.ownerDocument.createElement('a');
link.setAttribute('href', href.href);
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
link.textContent = img.getAttribute('alt')?.trim() || img.getAttribute('title')?.trim() || href.host;
img.replaceWith(link);
}
function isCopyCodeButton(button: HTMLButtonElement): boolean {
const wrapper = button.parentElement;
return button.classList.contains('clipboard-btn') && !!wrapper?.classList.contains('code-wrapper') &&
COPY_CODE_CLICK.test(wrapper.getAttribute('onclick')?.trim() ?? '');
}
function sanitizeStyle(style: string): string {
const declarations = style.split(';').map(declaration => declaration.trim()).filter(declaration => declaration);
const kept = declarations.filter(declaration => {
const colon = declaration.indexOf(':');
if (colon <= 0) {
return false;
}
const property = declaration.substring(0, colon).trim().toLowerCase();
const value = declaration.substring(colon + 1).trim().toLowerCase();
return ALLOWED_STYLE_PROPERTIES.has(property) && isSafeStyleValue(property, value);
});
return kept.length === declarations.length ? style : kept.join('; ');
}
function isSafeStyleValue(property: string, value: string): boolean {
if (!value || /[\\@<>"']|\/\*|url|expression|image|attr\s*\(/.test(value)) {
return false;
}
for (const call of value.matchAll(/([a-z-]+)\s*\(/g)) {
if (!ALLOWED_STYLE_FUNCTIONS.has(call[1])) {
return false;
}
}
return !(property.startsWith('margin') && value.includes('-'));
}

12
ui-ngx/src/app/shared/components/markdown.component.ts

@ -25,6 +25,7 @@ import { SHARED_MODULE_TOKEN } from '@shared/components/tokens';
import { guid, isDefinedAndNotNull } from '@core/utils'; import { guid, isDefinedAndNotNull } from '@core/utils';
import { Observable, of, ReplaySubject } from 'rxjs'; import { Observable, of, ReplaySubject } from 'rxjs';
import { coerceBoolean } from '@shared/decorators/coercion'; import { coerceBoolean } from '@shared/decorators/coercion';
import { sanitizeMarkdownHtml } from '@shared/components/markdown-html-sanitize';
import { sanitizeTemplate } from './markdown-sanitize.helper'; import { sanitizeTemplate } from './markdown-sanitize.helper';
let defaultMarkdownStyle: string; let defaultMarkdownStyle: string;
@ -68,6 +69,10 @@ export class TbMarkdownComponent implements OnChanges {
@coerceBoolean() @coerceBoolean()
usePlainMarkdown = false; usePlainMarkdown = false;
@Input()
@coerceBoolean()
sanitizeHtml = false;
@Input() @Input()
@coerceBoolean() @coerceBoolean()
highlight = true; highlight = true;
@ -106,7 +111,8 @@ export class TbMarkdownComponent implements OnChanges {
} }
private render(markdown: string) { private render(markdown: string) {
const compiled = this.markdownService.parse(markdown, { decodeHtml: false, disableSanitizer: true }); const parsed = this.markdownService.parse(markdown, { decodeHtml: false, disableSanitizer: true });
const compiled = this.sanitizeHtml ? sanitizeMarkdownHtml(parsed as string) : parsed;
let markdownClass = 'tb-markdown-view'; let markdownClass = 'tb-markdown-view';
if (this.markdownClass) { if (this.markdownClass) {
markdownClass += ` ${this.markdownClass}`; markdownClass += ` ${this.markdownClass}`;
@ -127,7 +133,7 @@ export class TbMarkdownComponent implements OnChanges {
const preHtml = preElements.item(i).outerHTML.replace('ngnonbindable=""', 'ngNonBindable'); const preHtml = preElements.item(i).outerHTML.replace('ngnonbindable=""', 'ngNonBindable');
template = template.replace(matches[i][0], preHtml); template = template.replace(matches[i][0], preHtml);
} }
template = sanitizeTemplate(template); template = this.sanitizeHtml ? sanitizeMarkdownHtml(template) : sanitizeTemplate(template);
this.markdownContainer.clear(); this.markdownContainer.clear();
let styles: string[] = []; let styles: string[] = [];
let readyObservable: Observable<void>; let readyObservable: Observable<void>;
@ -142,7 +148,7 @@ export class TbMarkdownComponent implements OnChanges {
if (this.additionalStyles) { if (this.additionalStyles) {
styles = styles.concat(this.additionalStyles); styles = styles.concat(this.additionalStyles);
} }
if (this.usePlainMarkdown) { if (this.usePlainMarkdown || this.sanitizeHtml) {
readyObservable = this.plainMarkdown(template, styles); readyObservable = this.plainMarkdown(template, styles);
this.cd.detectChanges(); this.cd.detectChanges();
readyObservable.subscribe(() => { readyObservable.subscribe(() => {

2
ui-ngx/src/app/shared/components/toast.directive.ts

@ -70,7 +70,7 @@ export class ToastDirective implements AfterViewInit, OnDestroy {
(hideNotification) => { (hideNotification) => {
if (hideNotification) { if (hideNotification) {
const target = hideNotification.target || 'root'; const target = hideNotification.target || 'root';
if (this.toastTarget === target) { if (this.toastTarget === target && (!hideNotification.message || this.currentMessage?.message === hideNotification.message)) {
this.currentMessage = null; this.currentMessage = null;
this.ngZone.run(() => { this.ngZone.run(() => {
if (this.snackBarRef) { if (this.snackBarRef) {

1
ui-ngx/src/app/shared/models/solution-creator.models.ts

@ -14,6 +14,7 @@ export const NEW_SOLUTION_ID = 'new';
export interface SolutionInfo { export interface SolutionInfo {
id: string; id: string;
createdTime?: number; createdTime?: number;
updatedTime?: number;
solutionTitle?: string; solutionTitle?: string;
installed?: boolean; installed?: boolean;
built?: boolean; built?: boolean;

11
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -3008,6 +3008,13 @@
"output": "Output", "output": "Output",
"severities": "Severities", "severities": "Severities",
"clears": "Clears", "clears": "Clears",
"rule-critical": "Critical when",
"rule-major": "Major when",
"rule-minor": "Minor when",
"rule-warning": "Warning when",
"rule-indeterminate": "Indeterminate when",
"clear-rule": "Clears when",
"filter": "Entities",
"undo": "Can be undone", "undo": "Can be undone",
"template": "Template", "template": "Template",
"recipients": "Recipients", "recipients": "Recipients",
@ -15858,7 +15865,9 @@
"no-roles": "No roles in this design.", "no-roles": "No roles in this design.",
"nothing-created": "Nothing is created yet.", "nothing-created": "Nothing is created yet.",
"not-installed": "The solution is created but not installed. Install it to make its entities in your tenant.", "not-installed": "The solution is created but not installed. Install it to make its entities in your tenant.",
"on": "On", "on": "Used for",
"op-all": "All operations",
"all-resources": "All resources",
"op-create": "Create", "op-create": "Create",
"op-read": "Read", "op-read": "Read",
"op-update": "Update", "op-update": "Update",

45
ui-ngx/src/theme/ai-theme.scss

@ -7,6 +7,8 @@
// one-off shades of the design (mostly on dark surfaces) stay literal. // one-off shades of the design (mostly on dark surfaces) stay literal.
// [data-ai] gives AI surfaces the AI's teal instead of the white-labeled primary palette, as the design specifies. // [data-ai] gives AI surfaces the AI's teal instead of the white-labeled primary palette, as the design specifies.
@use '../app/modules/home/components/ai/ai-breakpoints' as *;
:root { :root {
--tb-ink-76: rgba(0, 0, 0, 0.76); --tb-ink-76: rgba(0, 0, 0, 0.76);
--tb-ink-60: rgba(0, 0, 0, 0.6); --tb-ink-60: rgba(0, 0, 0, 0.6);
@ -475,31 +477,22 @@
} }
} }
@keyframes tb-ai-tip-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes tb-ai-tip-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.mat-mdc-tooltip.tb-ai-tip { .mat-mdc-tooltip.tb-ai-tip {
opacity: 0;
transform: scale(1) !important;
&.mat-mdc-tooltip-show { &.mat-mdc-tooltip-show {
animation: tb-ai-tip-in 100ms ease-out forwards; animation-duration: 100ms;
animation-timing-function: ease-out;
} }
&.mat-mdc-tooltip-hide { &.mat-mdc-tooltip-hide {
animation: tb-ai-tip-out 60ms ease-in forwards; animation-duration: 60ms;
animation-timing-function: ease-in;
}
&._mat-animation-noopable.mat-mdc-tooltip-show {
opacity: 1;
} }
} }
@ -2223,18 +2216,12 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); }
} }
} }
@container k-chat (max-width: 400px) { @container k-chat (max-width: #{$ai-composer-auto-label-max}) {
.tb-ai-composer .composer-foot:has(.cred.near, .cred.over) .composer-auto .label { .tb-ai-composer .composer-foot:has(.cred.near, .cred.over) .composer-auto .label {
display: none; display: none;
} }
} }
@container k-chat (max-width: 340px) {
.tb-ai-composer .cred:has(.cred-topup) .cred-line {
display: none;
}
}
.tb-ai-composer.docked .composer-auto { .tb-ai-composer.docked .composer-auto {
gap: 0; gap: 0;
@ -2263,9 +2250,7 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); }
width: 56px; width: 56px;
} }
} }
}
@container k-chat (max-width: 560px) {
.k-fields { .k-fields {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: 1px 0; gap: 1px 0;
@ -4230,7 +4215,7 @@ cursor: pointer;
vertical-align: 1px; vertical-align: 1px;
} }
.composer-ghost-end { .composer-ghost-end {
white-space: nowrap; white-space: nowrap;
} }

Loading…
Cancel
Save