Browse Source

Merge branch 'lts-4.4' into feature/ai-model-chat-by-ai

pull/16379/head
Kostenko Roman 1 month ago
committed by GitHub
parent
commit
25cdeece04
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 26
      CONTRIBUTING.md
  2. 4
      application/src/main/java/org/thingsboard/server/controller/AdminController.java
  3. 14
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  4. 11
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  5. 13
      application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java
  6. 2
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  7. 20
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  8. 48
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  9. 12
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  10. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java
  11. 41
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnLink.java
  12. 18
      application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeUplinkMessageDispatcher.java
  13. 9
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java
  14. 13
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/BaseUserProcessor.java
  15. 12
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/wl/WhiteLabelingEdgeProcessor.java
  16. 55
      application/src/main/java/org/thingsboard/server/service/edge/rpc/service/EdgeGrpcService.java
  17. 27
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java
  18. 230
      application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java
  19. 9
      application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java
  20. 67
      application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java
  21. 63
      application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java
  22. 38
      application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java
  23. 4
      application/src/main/resources/thingsboard.yml
  24. 7
      application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java
  25. 11
      application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
  26. 12
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerOnPremiseTest.java
  27. 42
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerTest.java
  28. 6
      application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java
  29. 10
      application/src/test/java/org/thingsboard/server/controller/TranslationControllerTest.java
  30. 40
      application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java
  31. 109
      application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java
  32. 198
      application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java
  33. 106
      application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java
  34. 72
      application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java
  35. 74
      application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
  36. 51
      application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
  37. 48
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  38. 95
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
  39. 10
      application/src/test/java/org/thingsboard/server/service/ai/transport/FakeTbAiServer.java
  40. 112
      application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java
  41. 40
      application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/wl/WhiteLabelingEdgeProcessorTest.java
  42. 250
      application/src/test/java/org/thingsboard/server/service/edge/rpc/service/EdgeGrpcServiceTest.java
  43. 52
      application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java
  44. 28
      common/edge-api/src/main/proto/edge.proto
  45. 159
      msa/js-executor/api/jsExecutor.ts
  46. 3
      msa/js-executor/config/logger.ts
  47. 2
      msa/js-executor/docker/Dockerfile
  48. 33
      msa/js-executor/package.json
  49. 2
      msa/js-executor/pom.xml
  50. 29
      msa/js-executor/test/coldPathProbe.ts
  51. 118
      msa/js-executor/test/jsExecutor.test.ts
  52. 1465
      msa/js-executor/yarn.lock
  53. 5
      msa/web-report/config/logger.ts
  54. 2
      msa/web-report/docker/Dockerfile
  55. 34
      msa/web-report/package.json
  56. 2
      msa/web-report/pom.xml
  57. 1280
      msa/web-report/yarn.lock
  58. 5
      msa/web-ui/config/logger.ts
  59. 2
      msa/web-ui/docker/Dockerfile
  60. 38
      msa/web-ui/package.json
  61. 2
      msa/web-ui/pom.xml
  62. 4
      msa/web-ui/server.ts
  63. 1285
      msa/web-ui/yarn.lock
  64. 2
      pom.xml
  65. 8
      tools/src/main/python/license-headers/curations.json
  66. 3
      ui-ngx/esbuild/tb-html-fallback-middleware.ts
  67. 97
      ui-ngx/package.json
  68. 0
      ui-ngx/patches/@angular+build+20.3.41.patch
  69. 0
      ui-ngx/patches/@angular+core+20.3.34.patch
  70. 0
      ui-ngx/patches/@iplab+ngx-color-picker+20.1.0.patch
  71. 2
      ui-ngx/pom.xml
  72. 14
      ui-ngx/src/app/core/http/ai-chat.service.ts
  73. 124
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  74. 5
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  75. 16
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  76. 69
      ui-ngx/src/app/modules/home/components/widget/lib/action/action-widget.models.ts
  77. 4
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-resources-tabs.component.html
  78. 36
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/get-value-action-settings-panel.component.html
  79. 29
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/get-value-action-settings-panel.component.ts
  80. 1
      ui-ngx/src/app/modules/home/components/widget/widget.component.ts
  81. 2
      ui-ngx/src/app/modules/home/home.component.html
  82. 2
      ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.html
  83. 5
      ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.scss
  84. 2146
      ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js
  85. 21
      ui-ngx/src/app/shared/models/action-widget-settings.models.ts
  86. 8
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  87. 4
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  88. 33
      ui-ngx/src/assets/help/en_US/widget/lib/rpc/rpc_params_fn.md
  89. 3
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  90. 12
      ui-ngx/src/scss/flags.scss
  91. 4994
      ui-ngx/yarn.lock

26
CONTRIBUTING.md

@ -157,6 +157,32 @@ Open a pull request against `master`. Fill out the pull request template, and ma
- The change builds cleanly: `mvn -pl <module> -am -DskipTests -Dpkg.skip=true test-compile` at minimum for the modules you touched.
- You have signed the Contributor License Agreement (see below).
### Pull request titles
The release notes are generated from pull request titles, word for word. Write the title for the
people who read them — users and customers, not reviewers:
- **Describe the change in behavior, as a user sees it.** Name the feature or screen and what now
works differently. Leave out class names, exceptions, library versions and other internals a
user can't relate to; they belong in the description.
- **Use the past tense, starting with a verb** such as `Fixed`, `Added`, `Updated`, `Improved`,
`Removed`, `Renamed` or `Made`. Not `Fix`, `Add` or `Update`.
- **Leave out code-scope prefixes and suffixes** such as `fix(ui):`, ticket keys or branch names
(`(lts-4.3)`). A product-area prefix a user recognizes is fine, followed by the verb:
`IoT Hub: added filtering of the catalogue by the creator's verification status`.
The section an entry appears under (`UI`, `Bug: UI`, `Edge`, …) comes from the pull request's
labels, not its title, so don't repeat the area or the change type in the title. Changes users
don't see — CI, build, a second backport of the same fix — get the `Ignore for release` label
and stay out of the release notes. For anything else, such as docs or refactoring, decide
whether users would want to read about it in the release notes, and add the label if not.
| Instead of | Write |
|----------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| `fix(ui): update moment-timezone to 0.6.5 (tzdata 2026e)` | `Updated UI time zone data to reflect 2026 daylight saving time changes in Canada, Morocco and Moldova` |
| `Warn that updating a solution template recreates everything it installed` | `Added a warning that updating a solution template recreates everything it installed` |
| `Fix empty Provisioning step when navigating the device install wizard via the stepper header` | `Fixed empty Provisioning step when navigating the device install wizard via the stepper header` |
## Contributor License Agreement
Before we can merge your pull request, you need to sign the ThingsBoard

4
application/src/main/java/org/thingsboard/server/controller/AdminController.java

@ -132,7 +132,7 @@ public class AdminController extends BaseController {
public AdminSettings getAdminSettings(
@Parameter(description = "A string value of the key (e.g. 'general' or 'mail').")
@PathVariable("key") String key,
@Parameter(description = "Use system settings if settings are not defined on tenant level.")
@Parameter(description = "Deprecated, not used.")
@RequestParam(required = false, defaultValue = "false") boolean systemByDefault) throws Exception {
Authority authority = getCurrentUser().getAuthority();
AdminSettings adminSettings;
@ -141,7 +141,7 @@ public class AdminController extends BaseController {
adminSettings = checkNotNull(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, key), "No Administration settings found for key: " + key);
} else {
accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.READ);
adminSettings = getTenantAdminSettings(getTenantId(), key, systemByDefault);
adminSettings = getTenantAdminSettings(getTenantId(), key, false);
}
if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) {
((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken");

14
application/src/main/java/org/thingsboard/server/controller/AiChatController.java

@ -109,6 +109,20 @@ class AiChatController extends BaseController {
return withTraceLogging(chatId, aiChatService.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, clientOrigin, user));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(value = "/{chatId}/resume", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> resumeChat(
@PathVariable UUID chatId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage,
HttpServletRequest httpRequest
) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
String clientOrigin = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest);
return withTraceLogging(chatId, aiChatService.resumeChat(chatId, tbAccessToken, acceptLanguage, clientOrigin, user));
}
private Flux<ServerSentEvent<String>> withTraceLogging(UUID chatId, Flux<ServerSentEvent<String>> events) {
return events.doOnNext(event -> {
if (log.isTraceEnabled()) {

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

@ -25,6 +25,7 @@ import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
@ -57,9 +58,12 @@ class DefaultTbAiService implements TbAiService {
}
@Override
public Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> call, SecurityUser user) {
public Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> call, SecurityUser user,
TbAiTurnLink link, boolean checkCredits) {
checkEnabled();
checkApiUsage(user);
if (checkCredits) {
checkApiUsage(user);
}
TbAiClient.TokenProvider tokenProvider = createCheckedTokenProvider(user);
return Flux.defer(() -> {
// Eager subscribe so client cancel does not drop the trailing creditsUsed event.
@ -85,7 +89,8 @@ class DefaultTbAiService implements TbAiService {
clientSink::tryEmitComplete
);
return clientSink.asFlux();
Flux<ServerSentEvent<String>> client = clientSink.asFlux();
return link != null ? client.doOnCancel(link::clientLeft) : client;
});
}

13
application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java

@ -7,6 +7,7 @@ import org.springframework.http.codec.ServerSentEvent;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import reactor.core.publisher.Flux;
import java.util.UUID;
@ -19,7 +20,17 @@ public interface TbAiService {
JsonNode process(TbAiCall<TbAiClient.TbAiResponse> action, SecurityUser user, boolean checkCredits);
Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user);
default Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user) {
return processStream(chatId, action, user, null, true);
}
/**
* Streams a chat turn to the browser. {@code link}, when given, is told when the browser stops listening, which
* ThingsBoard itself never does before the turn ends. {@code checkCredits} is false for following a turn that has
* already been paid for.
*/
Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user,
TbAiTurnLink link, boolean checkCredits);
boolean isEnabled();

2
application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java

@ -26,4 +26,6 @@ public interface AiChatService {
SecurityUser user
);
Flux<ServerSentEvent<String>> resumeChat(UUID chatId, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user);
}

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

@ -8,12 +8,14 @@ import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Flux;
@ -24,6 +26,8 @@ import java.util.UUID;
@RequiredArgsConstructor
class DefaultAiChatService implements AiChatService {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport;
private final TbAiOperations operations;
@ -49,7 +53,7 @@ class DefaultAiChatService implements AiChatService {
@Override
public JsonNode getChatMessages(UUID chatId, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false);
}
@Override
@ -63,10 +67,20 @@ class DefaultAiChatService implements AiChatService {
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
) {
var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
return tbAiTransport.sendChatMessage(chatId, request, context, link);
}, user, link, true);
}
@Override
public Flux<ServerSentEvent<String>> resumeChat(UUID chatId, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user) {
var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
return tbAiTransport.sendChatMessage(chatId, request, context);
}, user);
return tbAiTransport.resumeChat(chatId, context, link);
}, user, link, false);
}
}

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

@ -39,10 +39,22 @@ class ChannelTbAiTransport implements TbAiTransport {
private final TbAiRequestExecutor requestExecutor;
@Override
public Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context) {
public Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link) {
return turn(ChannelProtocol.CHAT_SEND, chatId, request, context, link);
}
@Override
public Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link) {
return turn(ChannelProtocol.CHAT_RESUME, chatId, null, context, link);
}
private Flux<ServerSentEvent<String>> turn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link) {
return Flux.create(sink -> {
var turn = new ChannelTurn(chatId, request, context, sink);
var turn = new ChannelTurn(type, chatId, request, context, sink);
sink.onDispose(turn::abandon);
if (link != null) {
link.onClientLeft(turn::detach);
}
turn.start(false);
});
}
@ -56,6 +68,7 @@ class ChannelTbAiTransport implements TbAiTransport {
private final class ChannelTurn implements TbAiChannelExchange {
private final String type;
private final UUID chatId;
private final JsonNode request;
private final TbAiTurnContext context;
@ -65,8 +78,10 @@ class ChannelTbAiTransport implements TbAiTransport {
private volatile String op;
private volatile boolean frameSeen;
private volatile boolean retried;
private volatile boolean detached;
private ChannelTurn(UUID chatId, JsonNode request, TbAiTurnContext context, FluxSink<ServerSentEvent<String>> sink) {
private ChannelTurn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, FluxSink<ServerSentEvent<String>> sink) {
this.type = type;
this.chatId = chatId;
this.request = request;
this.context = context;
@ -98,6 +113,23 @@ class ChannelTbAiTransport implements TbAiTransport {
end(null);
}
void detach() {
detached = true;
sendDetach();
}
private void sendDetach() {
TbAiPooledConnection current = connection;
if (finished.get() || current == null || !current.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) {
return;
}
try {
current.send(new ChannelFrame(ChannelProtocol.CHAT_DETACH, null, null, null, op));
} catch (ChannelException e) {
log.debug("[{}] Failed to detach from the AI turn: {}", chatId, e.getMessage());
}
}
@Override
public void onFrame(TbAiPooledConnection frameConnection, ChannelFrame frame) {
try {
@ -153,13 +185,21 @@ class ChannelTbAiTransport implements TbAiTransport {
acquired.unreserve(System.nanoTime());
return;
}
ChannelFrame start = ChannelFrame.request(ChannelProtocol.CHAT_SEND,
if (ChannelProtocol.CHAT_RESUME.equals(type) && !acquired.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) {
acquired.unreserve(System.nanoTime());
end(null);
return;
}
ChannelFrame start = ChannelFrame.request(type,
acquired.codec().toPayload(new ChatTurnRequest(chatId, request, context.acceptLanguage())))
.withOrigin(context.clientOrigin());
op = start.id();
connection = acquired;
try {
acquired.start(this, start);
if (detached) {
sendDetach();
}
} catch (ChannelException e) {
connection = null;
acquired.finish(op, System.nanoTime());

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

@ -53,6 +53,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
private volatile List<String> serverCapabilities = List.of();
/**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
@ -108,6 +109,14 @@ final class TbAiPooledConnection implements ChannelFrameListener {
return ready;
}
/**
* Whether TB AI listed {@code capability} in its hello. Frames a capability adds must not be sent without it: an
* older TB AI closes the connection on a frame type it does not know.
*/
boolean supports(String capability) {
return serverCapabilities.contains(capability);
}
/**
* The session arrived. If the handshake already failed (the connect timed out), the session is closed: it is
* stored first and {@link #failed} closes whatever is stored after failing {@code ready}, so one of the two always
@ -293,6 +302,9 @@ final class TbAiPooledConnection implements ChannelFrameListener {
if (hello.maxFrameBytes() != null && hello.maxFrameBytes() > 0 && hello.maxFrameBytes() < Integer.MAX_VALUE) {
maxFrameBytes = hello.maxFrameBytes().intValue();
}
if (hello.capabilities() != null) {
serverCapabilities = List.copyOf(hello.capabilities());
}
ready.complete(this);
}
case ChannelProtocol.ERROR -> {

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

@ -10,6 +10,12 @@ import java.util.UUID;
public interface TbAiTransport {
Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context);
Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link);
/**
* Follows the turn running in the chat: a {@code turnResumed} event, every event of the turn so far, then the live
* ones. Completes at once when no turn is running or when TB AI cannot resume turns.
*/
Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link);
}

41
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnLink.java

@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* Connects the browser end of an AI chat stream to its turn on TB AI. ThingsBoard keeps listening to a turn after the
* browser leaves (the turn bills its credits at its end), so leaving is reported separately: TB AI then knows nobody
* follows the turn, and a pending approval expires soon instead of waiting its full timeout for a user who left.
*/
public final class TbAiTurnLink {
private final Object lock = new Object();
private Runnable onClientLeft;
private boolean clientLeft;
public void onClientLeft(Runnable listener) {
boolean leftAlready;
synchronized (lock) {
onClientLeft = listener;
leftAlready = clientLeft;
}
if (leftAlready) {
listener.run();
}
}
public void clientLeft() {
Runnable listener;
synchronized (lock) {
if (clientLeft) {
return;
}
clientLeft = true;
listener = onClientLeft;
}
if (listener != null) {
listener.run();
}
}
}

18
application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeUplinkMessageDispatcher.java

@ -37,6 +37,9 @@ import org.thingsboard.server.gen.edge.v1.ResourceUpdateMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainMetadataUpdateMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg;
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SchedulerEventUpdateMsg;
import org.thingsboard.server.gen.edge.v1.UplinkMsg;
import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg;
@ -177,6 +180,21 @@ public class EdgeUplinkMessageDispatcher {
result.add(ctx.getEdgeRequestsService().processEntityViewsRequestMsg(edge.getTenantId(), edge, entityViewRequestMsg));
}
}
if (uplinkMsg.getSendEmailUplinkMsgCount() > 0) {
for (SendEmailUplinkMsg sendEmailUplinkMsg : uplinkMsg.getSendEmailUplinkMsgList()) {
result.add(ctx.getEdgeRequestsService().processSendEmailMsg(edge.getTenantId(), edge, sendEmailUplinkMsg));
}
}
if (uplinkMsg.getSendSmsUplinkMsgCount() > 0) {
for (SendSmsUplinkMsg sendSmsUplinkMsg : uplinkMsg.getSendSmsUplinkMsgList()) {
result.add(ctx.getEdgeRequestsService().processSendSmsMsg(edge.getTenantId(), edge, sendSmsUplinkMsg));
}
}
if (uplinkMsg.getSendNotificationUplinkMsgCount() > 0) {
for (SendNotificationUplinkMsg sendNotificationUplinkMsg : uplinkMsg.getSendNotificationUplinkMsgList()) {
result.add(ctx.getEdgeRequestsService().processSendNotificationMsg(edge.getTenantId(), edge, sendNotificationUplinkMsg));
}
}
if (uplinkMsg.getEntityGroupEntitiesRequestMsgCount() > 0) {
for (EntityGroupRequestMsg entityGroupEntitiesRequestMsg : uplinkMsg.getEntityGroupEntitiesRequestMsgList()) {
result.add(ctx.getEdgeRequestsService().processEntityGroupEntitiesRequest(edge.getTenantId(), edge, entityGroupEntitiesRequestMsg));

9
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java

@ -16,11 +16,15 @@ import org.thingsboard.server.gen.edge.v1.EdgeVersion;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor;
import java.util.Set;
@Slf4j
@Component
@TbCoreComponent
public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor {
private static final Set<String> EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity");
@Override
public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) {
AdminSettings adminSettings = null;
@ -34,6 +38,11 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor {
if (adminSettings == null) {
return null;
}
if (!EDGE_SYNCED_SETTINGS_KEYS.contains(adminSettings.getKey())) {
log.trace("Skipping admin settings [{}] sync to edge [{}] - not in the edge allow-list",
adminSettings.getKey(), edgeEvent.getEdgeId());
return null;
}
AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build();
return DownlinkMsg.newBuilder()
.setDownlinkMsgId(EdgeUtils.nextPositiveInt())

13
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/BaseUserProcessor.java

@ -17,8 +17,10 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.dao.service.DataValidator;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.gen.edge.v1.UserCredentialsUpdateMsg;
import org.thingsboard.server.gen.edge.v1.UserUpdateMsg;
import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor;
@ -44,8 +46,15 @@ public abstract class BaseUserProcessor extends BaseEdgeProcessor {
if (user == null) {
throw new IllegalArgumentException(String.format("[%s] Failed to parse User from UserUpdateMsg: %s", tenantId, userUpdateMsg));
}
if (user.getAuthority() != Authority.TENANT_ADMIN && user.getAuthority() != Authority.CUSTOMER_USER) {
throw new DataValidationException("User authority " + user.getAuthority() + " is not allowed!");
}
user.setTenantId(tenantId);
User userById = edgeCtx.getUserService().findUserById(tenantId, userId);
if (userById != null && !tenantId.equals(userById.getTenantId())) {
throw new DataValidationException("User " + userId + " belongs to a different tenant!");
}
if (userById == null) {
isCreated = true;
user.setId(null);
@ -118,7 +127,7 @@ public abstract class BaseUserProcessor extends BaseEdgeProcessor {
private User deleteUser(TenantId tenantId, UserId userId) throws ThingsboardException {
User userById = edgeCtx.getUserService().findUserById(tenantId, userId);
if (userById == null) {
if (userById == null || !tenantId.equals(userById.getTenantId())) {
log.trace("[{}] User with id {} does not exist", tenantId, userId);
return null;
}
@ -133,7 +142,7 @@ public abstract class BaseUserProcessor extends BaseEdgeProcessor {
throw new IllegalArgumentException(String.format("[%s] Failed to parse UserCredentials from updateMsg: %s", tenantId, updateMsg));
}
User user = edgeCtx.getUserService().findUserById(tenantId, userCredentials.getUserId());
if (user == null) {
if (user == null || !tenantId.equals(user.getTenantId())) {
log.warn("[{}] Can't find user by id [{}] skipping credentials update. UserCredentialsUpdateMsg [{}]",
tenantId, userCredentials.getUserId(), updateMsg);
return;

12
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/wl/WhiteLabelingEdgeProcessor.java

@ -65,6 +65,9 @@ public class WhiteLabelingEdgeProcessor extends BaseEdgeProcessor {
if (whiteLabeling == null) {
return null;
}
if (isSystemMailTemplates(whiteLabeling.getType(), tenantId)) {
return null;
}
UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction());
WhiteLabelingProto whiteLabelingProto = EdgeMsgConstructorUtils.constructWhiteLabeling(msgType, whiteLabeling);
DownlinkMsg.Builder builder = DownlinkMsg.newBuilder()
@ -80,6 +83,9 @@ public class WhiteLabelingEdgeProcessor extends BaseEdgeProcessor {
}
case DELETED -> {
WhiteLabeling whiteLabeling = JacksonUtil.convertValue(edgeEvent.getBody(), WhiteLabeling.class);
if (whiteLabeling != null && isSystemMailTemplates(whiteLabeling.getType(), whiteLabeling.getTenantId())) {
return null;
}
WhiteLabelingProto whiteLabelingProto = EdgeMsgConstructorUtils.constructWhiteLabeling(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, whiteLabeling);
return DownlinkMsg.newBuilder()
.setDownlinkMsgId(EdgeUtils.nextPositiveInt())
@ -92,6 +98,12 @@ public class WhiteLabelingEdgeProcessor extends BaseEdgeProcessor {
return null;
}
private boolean isSystemMailTemplates(WhiteLabelingType type, TenantId tenantId) {
// System mail templates are not synced to the Edge. The Edge is a thin mail client: it
// delegates every send to the Cloud, which renders with its own templates.
return WhiteLabelingType.MAIL_TEMPLATES.equals(type) && TenantId.SYS_TENANT_ID.equals(tenantId);
}
private WhiteLabelingType getWhiteLabelingType(EdgeEventType type) {
return switch (type) {
case WHITE_LABELING -> WhiteLabelingType.GENERAL;

55
application/src/main/java/org/thingsboard/server/service/edge/rpc/service/EdgeGrpcService.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.edge.rpc.service;
import com.fasterxml.jackson.databind.node.ObjectNode;
@ -39,9 +40,11 @@ import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg;
import org.thingsboard.server.common.msg.edge.EdgeSessionMsg;
import org.thingsboard.server.common.msg.edge.FromEdgeSyncResponse;
import org.thingsboard.server.common.msg.edge.ToEdgeSyncRequest;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.gen.edge.v1.EdgeRpcServiceGrpc;
import org.thingsboard.server.gen.edge.v1.RequestMsg;
import org.thingsboard.server.gen.edge.v1.ResponseMsg;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.edge.EdgeContextComponent;
@ -94,6 +97,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private final TbServiceInfoProvider serviceInfoProvider;
private final TelemetrySubscriptionService tsSubService;
private final TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache;
private final PartitionService partitionService;
private final ConcurrentMap<EdgeId, PendingDisconnect> pendingDisconnectNotifications = new ConcurrentHashMap<>();
private final ConcurrentMap<UUID, Consumer<FromEdgeSyncResponse>> localSyncEdgeRequests = new ConcurrentHashMap<>();
@ -198,20 +202,21 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
Edge edge = state.getEdge();
TenantId tenantId = state.getTenantId();
log.info("[{}][{}] edge [{}] connected successfully.", tenantId, state.getSessionId(), edgeId);
if (sessions.hasByEdgeId(edgeId)) {
EdgeGrpcSessionManager existingSession = sessions.getByEdgeId(edgeId);
if (existingSession != null) {
UUID sessionId = existingSession.getState().getSessionId();
log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, state.getSessionId(), sessionId, edgeId);
existingSession.destroyAndMarkAsZombieIfFailed();
sessions.removeBySessionId(sessionId);
}
// Swap first, destroy after: while the slow teardown runs, the replaced session is no longer current, so its own
// late disconnect takes the stale-session path instead of clearing the state of this connect.
EdgeGrpcSessionManager replaced = sessions.put(edgeSession);
if (replaced != null) {
UUID replacedSessionId = replaced.getState().getSessionId();
log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, state.getSessionId(), replacedSessionId, edgeId);
sessions.removeBySessionId(replacedSessionId);
replaced.destroyAndMarkAsZombieIfFailed();
}
sessions.put(edgeSession);
// Claim ownership before active=true: the previous node reads this entry on disconnect to decide
// whether to clear the flag.
edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId());
save(tenantId, edgeId, ACTIVITY_STATE, true);
long lastConnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs);
edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId());
// If the edge reconnected within the disconnect-notification delay window, suppress the pending
// "disconnected" notification - the drop was transient (debounce for flapping edges).
cancelPendingDisconnectNotification(edgeId);
@ -228,11 +233,14 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
EdgeGrpcSessionManager toRemove = sessions.removeByEdgeIdIfCurrent(edgeId, sessionId);
if (toRemove != null) {
sessions.removeBySessionId(sessionId);
save(tenantId, edgeId, ACTIVITY_STATE, false);
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
scheduleDisconnectNotification(edge);
// Skip all disconnect side effects if a newer session already owns the edge, on this or another node.
// The local check and the inactive write are atomic with a same-node reconnect.
if (!isOwnedByAnotherNode(edgeId) && sessions.runIfNoSession(edgeId, () -> save(tenantId, edgeId, ACTIVITY_STATE, false))) {
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
scheduleDisconnectNotification(edge);
}
toRemove.onEdgeDisconnect();
// keep the slow teardown last, after the state transition is fully recorded
toRemove.destroyAndMarkAsZombieIfFailed();
@ -427,6 +435,21 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get());
}
// The edge's cache entry names another node that is still a live TB-Core service. No entry, or an entry naming
// a node that has left the cluster, does not count: the cache has no TTL by default and only the owner evicts it,
// so honouring a dead owner would keep the edge marked active forever.
private boolean isOwnedByAnotherNode(EdgeId edgeId) {
TbCacheValueWrapper<String> wrapper = edgeIdServiceIdCache.get(edgeId);
if (wrapper == null) {
return false;
}
String ownerServiceId = wrapper.get();
if (ownerServiceId == null || serviceInfoProvider.getServiceId().equals(ownerServiceId)) {
return false;
}
return partitionService.getAllServiceIds(ServiceType.TB_CORE).contains(ownerServiceId);
}
// The edge has a live owner somewhere in the cluster (the cache is cluster-wide), regardless of which node.
private boolean isConnectedClusterWide(EdgeId edgeId) {
return edgeIdServiceIdCache.get(edgeId) != null;

27
application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.edge.rpc.session;
import lombok.Data;
@ -16,6 +17,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
@ -36,11 +38,14 @@ public class EdgeSessionsHolder {
unique.forEach(consumer);
}
public void put(EdgeGrpcSessionManager session) {
/**
* Registers the session as the current one for its edge and returns the session it replaced, or null.
*/
public EdgeGrpcSessionManager put(EdgeGrpcSessionManager session) {
UUID sessionId = session.getState().getSessionId();
EdgeId edgeId = session.getState().getEdgeId();
sessionsById.put(sessionId, session);
sessions.put(edgeId, session);
return sessions.put(edgeId, session);
}
public EdgeGrpcSessionManager getByEdgeId(EdgeId id) {
@ -88,6 +93,22 @@ public class EdgeSessionsHolder {
return removed.get();
}
/**
* Runs the action only if no session is registered for the edge, as one atomic step with {@link #put}.
* Returns whether it ran. The action holds the bin lock of {@link #sessions}, so it must be cheap and non-blocking.
*/
public boolean runIfNoSession(EdgeId id, Runnable action) {
AtomicBoolean ran = new AtomicBoolean();
sessions.compute(id, (edgeId, current) -> {
if (current == null) {
action.run();
ran.set(true);
}
return current;
});
return ran.get();
}
public EdgeGrpcSessionManager removeBySessionId(UUID sessionId) {
return sessionsById.remove(sessionId);
}

230
application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java

@ -10,11 +10,21 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.MessagingErrorCode;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.ListeningExecutor;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.rule.engine.api.SmsService;
import org.thingsboard.rule.engine.api.notification.FirebaseService;
import org.thingsboard.rule.engine.api.notification.SlackService;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.DataConstants;
@ -44,6 +54,11 @@ import org.thingsboard.server.common.data.id.WidgetsBundleId;
import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.common.data.kv.DataType;
import org.thingsboard.server.common.data.kv.TsKvEntry;
import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod;
import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.settings.NotificationSettings;
import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.targets.slack.SlackFile;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.GroupPermission;
@ -58,15 +73,17 @@ import org.thingsboard.server.common.data.widget.WidgetType;
import org.thingsboard.server.common.data.widget.WidgetsBundle;
import org.thingsboard.server.dao.asset.AssetService;
import org.thingsboard.server.dao.attributes.AttributesService;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.edge.EdgeEventService;
import org.thingsboard.server.dao.exception.IncorrectParameterException;
import org.thingsboard.server.dao.group.EntityGroupService;
import org.thingsboard.server.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.notification.NotificationSettingsService;
import org.thingsboard.server.dao.relation.RelationService;
import org.thingsboard.server.dao.role.RoleService;
import org.thingsboard.server.dao.secret.SecretConfigurationService;
import org.thingsboard.server.dao.timeseries.TimeseriesService;
import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.dao.widget.WidgetTypeService;
@ -78,18 +95,30 @@ import org.thingsboard.server.gen.edge.v1.EntityGroupRequestMsg;
import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg;
import org.thingsboard.server.gen.edge.v1.RelationRequestMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg;
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg;
import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg;
import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService;
import org.thingsboard.server.service.executors.DbCallbackExecutorService;
import org.thingsboard.server.service.executors.NotificationExecutorService;
import org.thingsboard.server.service.mail.EdgeMailRequest;
import org.thingsboard.server.service.mail.MailExecutorService;
import org.thingsboard.server.service.notification.EdgeNotificationRequest;
import org.thingsboard.server.service.sms.EdgeSmsRequest;
import org.thingsboard.server.service.sms.SmsExecutorService;
import org.thingsboard.server.service.state.DefaultDeviceStateService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
@ -145,6 +174,44 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService {
@Autowired
private DbCallbackExecutorService dbCallbackExecutorService;
@Autowired
private MailService mailService;
@Autowired
private SmsService smsService;
@Autowired
private SlackService slackService;
@Autowired
private FirebaseService firebaseService;
@Autowired
private NotificationSettingsService notificationSettingsService;
@Autowired
private SecretConfigurationService secretConfigurationService;
@Autowired
private MailExecutorService mailExecutor;
@Autowired
private SmsExecutorService smsExecutor;
@Autowired
private NotificationExecutorService notificationExecutor;
@Value("${edges.rpc.delegated_send_timeout_sec:20}")
private int delegatedSendTimeoutSec;
private final ScheduledExecutorService sendTimeoutScheduler =
ThingsBoardExecutors.newSingleThreadScheduledExecutor("edge-delegated-send-watchdog");
@PreDestroy
public void destroy() {
sendTimeoutScheduler.shutdownNow();
}
@Override
public ListenableFuture<Void> processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) {
log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg);
@ -691,6 +758,162 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService {
return Futures.immediateFuture(null);
}
@Override
public ListenableFuture<Void> processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) {
return submitEdgeSend(tenantId, edge, "email", mailExecutor, () -> sendEmailForEdge(tenantId, sendEmailUplinkMsg));
}
private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception {
EdgeMailRequest request = parseSendRequest(sendEmailUplinkMsg.getRequest(), EdgeMailRequest.class);
if (request == null || request.getMethod() == null) {
log.warn("[{}] Received empty send email request from edge", tenantId);
return;
}
switch (request.getMethod()) {
case SEND_BASIC ->
mailService.sendEmail(tenantId, request.getTo(), request.getSubject(), request.getMessage());
case SEND_TB_EMAIL ->
mailService.send(tenantId, null, request.getTbEmail());
case ACTIVATION ->
mailService.sendActivationEmail(tenantId, request.getActivationLink(), request.getTtlMs(), request.getTo());
case ACCOUNT_ACTIVATED ->
mailService.sendAccountActivatedEmail(tenantId, request.getLoginLink(), request.getTo());
case RESET_PASSWORD ->
mailService.sendResetPasswordEmail(tenantId, request.getPasswordResetLink(), request.getTtlMs(), request.getTo());
case PASSWORD_WAS_RESET ->
mailService.sendPasswordWasResetEmail(tenantId, request.getLoginLink(), request.getTo());
case TWO_FA ->
mailService.sendTwoFaVerificationEmail(tenantId, request.getTo(), request.getVerificationCode(), request.getExpirationTimeSeconds());
case ACCOUNT_LOCKOUT ->
mailService.sendAccountLockoutEmail(tenantId, request.getLockoutEmail(), request.getTo(), request.getMaxFailedLoginAttempts());
case API_USAGE_STATE ->
mailService.sendApiFeatureStateEmail(tenantId, request.getApiFeature(), request.getStateValue(), request.getTo(), request.getRecordState());
case TEST_MAIL ->
mailService.sendTestMail(tenantId, request.getTestConfig(), request.getTo());
}
}
@Override
public ListenableFuture<Void> processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) {
return submitEdgeSend(tenantId, edge, "sms", smsExecutor, () -> sendSmsForEdge(tenantId, sendSmsUplinkMsg));
}
private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception {
EdgeSmsRequest request = parseSendRequest(sendSmsUplinkMsg.getRequest(), EdgeSmsRequest.class);
if (request == null || request.getMethod() == null) {
log.warn("[{}] Received empty send sms request from edge", tenantId);
return;
}
switch (request.getMethod()) {
case SEND_SMS ->
smsService.sendSms(tenantId, null, request.getNumbers(), request.getMessage());
case SEND_TEST_SMS ->
smsService.sendTestSms(tenantId, request.getTestSmsRequest());
}
}
@Override
public ListenableFuture<Void> processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) {
return submitEdgeSend(tenantId, edge, "notification", notificationExecutor, () -> sendNotificationForEdge(tenantId, sendNotificationUplinkMsg));
}
private ListenableFuture<Void> submitEdgeSend(TenantId tenantId, Edge edge, String what,
ListeningExecutor executor, EdgeSendTask task) {
log.trace("[{}] processing edge-delegated {} send [{}]", tenantId, what, edge.getName());
ListenableFuture<Void> future = Futures.withTimeout(executor.submit(() -> {
task.execute();
return null;
}), delegatedSendTimeoutSec, TimeUnit.SECONDS, sendTimeoutScheduler);
Futures.addCallback(future, new FutureCallback<>() {
@Override
public void onSuccess(@Nullable Void result) {
}
@Override
public void onFailure(Throwable t) {
log.warn("[{}] Failed to send {} requested by edge [{}]", tenantId, what, edge.getName(), t);
}
}, dbCallbackExecutorService);
return future;
}
private void sendNotificationForEdge(TenantId tenantId, SendNotificationUplinkMsg sendNotificationUplinkMsg) throws Exception {
EdgeNotificationRequest request = parseSendRequest(sendNotificationUplinkMsg.getRequest(), EdgeNotificationRequest.class);
if (request == null || request.getMethod() == null) {
log.warn("[{}] Received empty send notification request from edge", tenantId);
return;
}
switch (request.getMethod()) {
case SEND_SLACK -> sendSlackForEdge(tenantId, request);
case SEND_MOBILE_PUSH -> sendMobilePushForEdge(tenantId, request);
}
}
private void sendSlackForEdge(TenantId tenantId, EdgeNotificationRequest request) {
SlackNotificationDeliveryMethodConfig config = getSlackConfig(tenantId);
if (config == null) {
log.warn("[{}] Slack is not configured on the cloud; dropping edge-delegated notification", tenantId);
return;
}
List<SlackFile> files = null;
if (request.getFiles() != null) {
files = request.getFiles().stream()
.map(file -> SlackFile.builder().name(file.getName()).type(file.getType()).data(file.getData()).build())
.toList();
}
slackService.sendMessage(tenantId, config.getBotToken(), request.getConversationId(), request.getMessage(), files);
}
private void sendMobilePushForEdge(TenantId tenantId, EdgeNotificationRequest request) throws Exception {
MobileAppNotificationDeliveryMethodConfig config = getMobileAppConfig(tenantId);
if (config == null || request.getFcmTokens() == null) {
log.warn("[{}] Mobile app notifications are not configured on the cloud; dropping edge-delegated push", tenantId);
return;
}
String credentials = config.getFirebaseServiceAccountCredentials();
for (String fcmToken : request.getFcmTokens()) {
try {
firebaseService.sendMessage(tenantId, credentials, fcmToken, request.getSubject(), request.getBody(), request.getData(), request.getBadge());
} catch (FirebaseMessagingException e) {
MessagingErrorCode errorCode = e.getMessagingErrorCode();
if (MessagingErrorCode.UNREGISTERED == errorCode || MessagingErrorCode.INVALID_ARGUMENT == errorCode
|| MessagingErrorCode.SENDER_ID_MISMATCH == errorCode) {
log.debug("[{}] Edge-delegated push rejected, FCM token is no longer valid: {}", tenantId, errorCode);
continue;
}
throw e;
}
}
}
private SlackNotificationDeliveryMethodConfig getSlackConfig(TenantId tenantId) {
NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId);
SlackNotificationDeliveryMethodConfig config = (SlackNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK);
if (config == null) {
return null;
}
return secretConfigurationService.replaceSecretUsages(tenantId, config, SlackNotificationDeliveryMethodConfig.class);
}
private MobileAppNotificationDeliveryMethodConfig getMobileAppConfig(TenantId tenantId) {
NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId);
boolean isSystem = false;
var config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP);
if (!tenantId.isSysTenantId() && (config == null || config.isUseSystemSettings())) {
settings = notificationSettingsService.findNotificationSettings(TenantId.SYS_TENANT_ID);
config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP);
isSystem = true;
}
if (config == null) {
return null;
}
return secretConfigurationService.replaceSecretUsages(isSystem ? TenantId.SYS_TENANT_ID : tenantId, config, MobileAppNotificationDeliveryMethodConfig.class);
}
private static <T> T parseSendRequest(String request, Class<T> clazz) throws IOException {
return request != null ? JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER.readValue(request, clazz) : null;
}
private ListenableFuture<Void> saveEdgeEvent(TenantId tenantId,
EdgeId edgeId,
EdgeEventType type,
@ -713,4 +936,9 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService {
return edgeEventService.saveAsync(edgeEvent);
}
@FunctionalInterface
private interface EdgeSendTask {
void execute() throws Exception;
}
}

9
application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java

@ -13,6 +13,9 @@ import org.thingsboard.server.gen.edge.v1.EntityGroupRequestMsg;
import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg;
import org.thingsboard.server.gen.edge.v1.RelationRequestMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg;
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg;
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg;
import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg;
import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg;
@ -42,4 +45,10 @@ public interface EdgeRequestsService {
ListenableFuture<Void> processEntityGroupEntitiesRequest(TenantId tenantId, Edge edge, EntityGroupRequestMsg entityGroupEntitiesRequestMsg);
ListenableFuture<Void> processEntityGroupPermissionsRequest(TenantId tenantId, Edge edge, EntityGroupRequestMsg userGroupEntitiesRequestMsg);
ListenableFuture<Void> processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg);
ListenableFuture<Void> processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg);
ListenableFuture<Void> processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg);
}

67
application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java

@ -0,0 +1,67 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.mail;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.rule.engine.api.TbEmail;
import org.thingsboard.server.common.data.ApiFeature;
import org.thingsboard.server.common.data.ApiUsageRecordState;
import org.thingsboard.server.common.data.ApiUsageStateValue;
/**
* Describes a mail send that the Edge delegates to the Cloud. On the Edge, a mail send that depends
* on admin-configured (tenant/system) mail settings is packaged into this request and enqueued as a
* SEND_EMAIL cloud event. On the Cloud, {@code method} selects the matching {@code MailService} call
* so the Cloud resolves the config, renders the template and transmits via its own SMTP.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EdgeMailRequest {
public enum MailMethod {
SEND_BASIC, // sendEmail(to, subject, message)
SEND_TB_EMAIL, // send(TbEmail)
ACTIVATION, // sendActivationEmail(activationLink, ttlMs, to)
ACCOUNT_ACTIVATED, // sendAccountActivatedEmail(loginLink, to)
RESET_PASSWORD, // sendResetPasswordEmail(passwordResetLink, ttlMs, to)
PASSWORD_WAS_RESET,// sendPasswordWasResetEmail(loginLink, to)
TWO_FA, // sendTwoFaVerificationEmail(to, verificationCode, expirationTimeSeconds)
ACCOUNT_LOCKOUT, // sendAccountLockoutEmail(lockoutEmail, to, maxFailedLoginAttempts)
API_USAGE_STATE, // sendApiFeatureStateEmail(apiFeature, stateValue, to, recordState)
TEST_MAIL // sendTestMail(config, to)
}
private MailMethod method;
private String to;
private String subject;
private String message;
private TbEmail tbEmail;
private String activationLink;
private String loginLink;
private String passwordResetLink;
private Long ttlMs;
private String verificationCode;
private Integer expirationTimeSeconds;
private String lockoutEmail;
private Integer maxFailedLoginAttempts;
private ApiFeature apiFeature;
private ApiUsageStateValue stateValue;
private ApiUsageRecordState recordState;
private JsonNode testConfig;
}

63
application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java

@ -0,0 +1,63 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.notification;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Describes a notification delivery that the Edge delegates to the Cloud, for channels whose credentials
* live only on the Cloud (they are stored in the {@code notifications} admin settings that no longer sync
* to the Edge). {@code method} selects the channel:
* <ul>
* <li>{@code SEND_SLACK} - the Cloud resolves the Slack bot token and posts {@code message} (plus any
* {@code files}) to {@code conversationId}. The whole send is delegated.</li>
* <li>{@code SEND_MOBILE_PUSH} - the Edge keeps the notification record, device-token lookup and unread
* count locally and delegates only the FCM push: the Cloud resolves the Firebase credentials and pushes
* the already-built payload ({@code subject}/{@code body}/{@code data}/{@code badge}) to every
* {@code fcmToken}.</li>
* </ul>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EdgeNotificationRequest {
public enum NotificationMethod {
SEND_SLACK,
SEND_MOBILE_PUSH
}
private NotificationMethod method;
// SEND_SLACK
private String conversationId;
private String message;
private List<SlackFileData> files;
// SEND_MOBILE_PUSH
private Set<String> fcmTokens;
private String subject;
private String body;
private Map<String, String> data;
private Integer badge;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class SlackFileData {
private String name;
private String type;
private byte[] data;
}
}

38
application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java

@ -0,0 +1,38 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.sms;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.sms.config.TestSmsRequest;
/**
* Describes an SMS send that the Edge delegates to the Cloud. On the Edge, a send that depends on
* admin-configured (tenant/system) SMS provider settings cannot be resolved locally, so the call is
* packaged into this request and enqueued as a SEND_SMS cloud event; on the Cloud, {@code method}
* selects the matching {@code SmsService} call so the Cloud resolves the config and transmits via its
* own provider.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EdgeSmsRequest {
public enum SmsMethod {
SEND_SMS, // sendSms(customerId, numbersTo, message)
SEND_TEST_SMS // sendTestSms(testSmsRequest)
}
private SmsMethod method;
private String[] numbers;
private String message;
private TestSmsRequest testSmsRequest;
}

4
application/src/main/resources/thingsboard.yml

@ -2020,6 +2020,10 @@ edges:
max_inbound_message_size: "${EDGES_RPC_MAX_INBOUND_MESSAGE_SIZE:4194304}"
# Maximum length of telemetry (time-series and attributes) message the cloud sends to the edge. By default, there is no limitation.
max_telemetry_message_size: "${EDGES_RPC_MAX_TELEMETRY_MESSAGE_SIZE:0}"
# Maximum time the cloud spends on a mail/SMS/notification send delegated by the edge before failing it.
# Must stay below the edge's 'cloud.uplink_pack_timeout_sec' (60 seconds by default): if the uplink is not
# answered in time the edge resends everything still unacknowledged, which delivers the same mail or SMS twice.
delegated_send_timeout_sec: "${EDGES_RPC_DELEGATED_SEND_TIMEOUT_SEC:20}"
storage:
# Max records of edge event to read from DB and sent to the edge
max_read_records_count: "${EDGES_STORAGE_MAX_READ_RECORDS_COUNT:50}"

7
application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java

@ -127,6 +127,13 @@ public abstract class AbstractAiControllerTest extends AbstractControllerTest {
.put("content", content);
}
protected MockHttpServletRequestBuilder resumeRequest(UUID chatId) {
MockHttpServletRequestBuilder request = post("/api/ai/chats/" + chatId + "/resume")
.accept(MediaType.TEXT_EVENT_STREAM);
setJwtToken(request);
return request;
}
protected MockHttpServletRequestBuilder sendMessageRequest(UUID chatId, JsonNode body, String acceptLanguage) {
MockHttpServletRequestBuilder request = post("/api/ai/chats/" + chatId + "/messages")
.contentType(MediaType.APPLICATION_JSON)

11
application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java

@ -175,6 +175,17 @@ public class AdminControllerTest extends AbstractControllerTest {
loginTenantAdmin();
}
@Test
public void testGetTenantAdminSettings() throws Exception {
loginTenantAdmin();
for (String key : new String[]{"jwt", "mail", "general"}) {
AdminSettings adminSettings = doGet("/api/admin/settings/" + key + "?systemByDefault=true", AdminSettings.class);
assertThat(adminSettings.getTenantId()).isEqualTo(tenantId);
assertThat(adminSettings.getKey()).isEqualTo(key);
assertThat(adminSettings.getJsonValue().isEmpty()).isTrue();
}
}
@Test
public void testGetAndSaveDefaultJwtSettings() throws Exception {
JwtSettings jwtSettings;

12
application/src/test/java/org/thingsboard/server/controller/AiChatControllerOnPremiseTest.java

@ -3,8 +3,10 @@
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.junit.Test;
@ -29,6 +31,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@DaoSqlTest
public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiControllerTest {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
@Test
public void shouldCreateChatWithOnPremiseToken_whenTenantAdmin() throws Exception {
// GIVEN
@ -83,13 +87,13 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID chatId = UUID.randomUUID();
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), success(JacksonUtil.newArrayNode()));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS), success(JacksonUtil.newArrayNode()));
// WHEN
doGet("/api/ai/chats/" + chatId + "/messages").andExpect(status().isOk());
// THEN
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@ -117,7 +121,7 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
UUID chatId = UUID.randomUUID();
ObjectNode requestBody = sendMessageBody("What is the device status?", null);
String acceptLanguage = "es-ES";
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class)))
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class), any(TbAiTurnLink.class)))
.willReturn(Flux.just(ServerSentEvent.<String>builder().event("message").data("Checking device status...").build()));
// WHEN
@ -128,7 +132,7 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
// THEN
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture());
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture(), any(TbAiTurnLink.class));
assertThat(context.getValue().tbAccessToken()).isEqualTo("Bearer " + token);
assertThat(context.getValue().acceptLanguage()).isEqualTo(acceptLanguage);
assertTokenProviderBelongsToTenantAdmin(context.getValue().tokenProvider());

42
application/src/test/java/org/thingsboard/server/controller/AiChatControllerTest.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
@ -40,6 +41,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@DaoSqlTest
public class AiChatControllerTest extends AbstractAiControllerTest {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
@MockitoBean
private TbApiUsageReportClient apiUsageReportClient;
@ -103,14 +106,14 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
ArrayNode messages = chatMessages();
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), success(messages));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS), success(messages));
// WHEN
JsonNode result = doGet("/api/ai/chats/" + chatId + "/messages", JsonNode.class);
// THEN
assertThat(result).isEqualTo(messages);
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS));
}
@Test
@ -138,7 +141,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
ServerSentEvent.<String>builder().event("message").data("Creating a high-temperature alarm rule...").build(),
ServerSentEvent.<String>builder().event("creditsUsed").data("{\"creditsUsed\":5}").build()
);
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class))).willReturn(upstream);
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class), any(TbAiTurnLink.class))).willReturn(upstream);
// WHEN
MvcResult asyncStart = mockMvc.perform(sendMessageRequest(chatId, requestBody, acceptLanguage))
@ -156,12 +159,39 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
verify(apiUsageReportClient).report(any(), any(), eq(ApiUsageRecordKey.AI_CREDITS_COUNT), eq(5L));
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture());
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture(), any(TbAiTurnLink.class));
assertThat(context.getValue().tbAccessToken()).isEqualTo("Bearer " + token);
assertThat(context.getValue().acceptLanguage()).isEqualTo(acceptLanguage);
assertTokenProviderBelongsToTenantAdmin(context.getValue().tokenProvider());
}
@Test
public void shouldStreamTheResumedTurnWithoutCheckingCredits_whenResumeChat() throws Exception {
// GIVEN — the browser reloaded while the assistant was still working, and AI credits ran out meanwhile
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
givenAiCreditsExhausted();
Flux<ServerSentEvent<String>> upstream = Flux.just(
ServerSentEvent.<String>builder().event("turnResumed").data("{}").build(),
ServerSentEvent.<String>builder().event("assistantMessage").data("{\"message\":\"Done.\"}").build()
);
given(tbAiTransport.resumeChat(eq(chatId), any(TbAiTurnContext.class), any(TbAiTurnLink.class))).willReturn(upstream);
// WHEN
MvcResult asyncStart = mockMvc.perform(resumeRequest(chatId))
.andExpect(request().asyncStarted())
.andReturn();
String body = mockMvc.perform(asyncDispatch(asyncStart))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
// THEN
assertThat(body).contains("event:turnResumed", "Done.");
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiTransport).resumeChat(eq(chatId), context.capture(), any(TbAiTurnLink.class));
assertThat(context.getValue().tbAccessToken()).isEqualTo("Bearer " + token);
}
// ------------------------------------------------------------------------
// AI credit-check semantics
// ------------------------------------------------------------------------
@ -224,7 +254,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
String error = "Chat service unavailable";
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), failure(error));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS), failure(error));
// WHEN
doGet("/api/ai/chats/" + chatId + "/messages")
@ -232,7 +262,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(error)));
// THEN
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS));
}
// ------------------------------------------------------------------------

6
application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java

@ -85,8 +85,8 @@ import org.thingsboard.server.dao.edge.EdgeDao;
import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.edge.imitator.EdgeImitator;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.gen.edge.v1.AssetProfileUpdateMsg;
import org.thingsboard.server.gen.edge.v1.AssetUpdateMsg;
import org.thingsboard.server.gen.edge.v1.CustomTranslationUpdateMsg;
@ -1047,9 +1047,7 @@ public class EdgeControllerTest extends AbstractControllerTest {
Assert.assertTrue(popRuleChainMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Edge Root Rule Chain"));
Assert.assertTrue(popRuleChainMetadataMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, getEdgeRootRuleChainId(edgeImitator)));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "general"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "mail"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "connectivity"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "jwt"));
Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default"));
Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default"));
Assert.assertTrue(popAssetProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default"));
@ -1770,9 +1768,7 @@ public class EdgeControllerTest extends AbstractControllerTest {
Assert.assertTrue(popTenantProfileMsg(edgeImitator.getDownlinkMsgsDeque(), tenantProfileId));
Assert.assertTrue(popQueueMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Main"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "general"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "mail"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "connectivity"));
Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "jwt"));
Assert.assertTrue(popRuleChainMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Edge Root Rule Chain"));
Assert.assertTrue(popRuleChainMetadataMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, getEdgeRootRuleChainId(edgeImitator)));
Assert.assertTrue(popRoleMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Tenant User", RoleType.GENERIC));

10
application/src/test/java/org/thingsboard/server/controller/TranslationControllerTest.java

@ -80,7 +80,7 @@ public class TranslationControllerTest extends AbstractControllerTest {
JsonNode fullSystemTranslation = doGet("/api/translation/full/" + ES_ES, JsonNode.class);
assertThat(fullSystemTranslation.get("save").asText()).isEqualTo("system");
assertThat(fullSystemTranslation.get("access").get("unauthorized").asText()).isEqualTo("No autorizado");
assertThat(fullSystemTranslation.get("solution-template").get("solution-template").asText()).isEqualTo("Plantilla de solución");
assertThat(fullSystemTranslation.get("device").get("device").asText()).isEqualTo("Dispositivo");
// get full tenant translation
loginTenantAdmin();
@ -88,7 +88,7 @@ public class TranslationControllerTest extends AbstractControllerTest {
assertThat(fullTenantTranslation.get("save").asText()).isEqualTo("system");
assertThat(fullTenantTranslation.get("update").asText()).isEqualTo("tenant");
assertThat(fullTenantTranslation.get("access").get("unauthorized").asText()).isEqualTo("No autorizado");
assertThat(fullTenantTranslation.get("solution-template").get("solution-template").asText()).isEqualTo("Plantilla de solución");
assertThat(fullTenantTranslation.get("device").get("device").asText()).isEqualTo("Dispositivo");
// get full customer custom translation
loginCustomerAdminUser();
@ -97,7 +97,7 @@ public class TranslationControllerTest extends AbstractControllerTest {
assertThat(fullCustomerTranslation.get("update").asText()).isEqualTo("tenant");
assertThat(fullCustomerTranslation.get("remove").asText()).isEqualTo("customer");
assertThat(fullCustomerTranslation.get("access").get("unauthorized").asText()).isEqualTo("No autorizado");
assertThat(fullCustomerTranslation.get("solution-template").get("solution-template").asText()).isEqualTo("Plantilla de solución");
assertThat(fullCustomerTranslation.get("device").get("device").asText()).isEqualTo("Dispositivo");
// get full subcustomer custom translation
loginSubCustomerAdminUser();
@ -107,7 +107,7 @@ public class TranslationControllerTest extends AbstractControllerTest {
assertThat(fullSubCustomerTranslation.get("remove").asText()).isEqualTo("customer");
assertThat(fullSubCustomerTranslation.get("search").asText()).isEqualTo("subCustomer");
assertThat(fullSubCustomerTranslation.get("access").get("unauthorized").asText()).isEqualTo("No autorizado");
assertThat(fullSubCustomerTranslation.get("solution-template").get("solution-template").asText()).isEqualTo("Plantilla de solución");
assertThat(fullSubCustomerTranslation.get("device").get("device").asText()).isEqualTo("Dispositivo");
}
@Test
@ -396,7 +396,7 @@ public class TranslationControllerTest extends AbstractControllerTest {
assertThat(downloadedCustomTranslation.get("save").asText()).isEqualTo("system");
assertThat(downloadedCustomTranslation.get("access").get("unauthorized").asText()).isEqualTo("No autorizado");
assertThat(downloadedCustomTranslation.get("solution-template").get("solution-template").asText()).isEqualTo("Plantilla de solución");
assertThat(downloadedCustomTranslation.get("device").get("device").asText()).isEqualTo("Dispositivo");
}
@Test

40
application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java

@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EdgeUtils;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.EntityView;
@ -105,6 +106,7 @@ import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg;
import org.thingsboard.server.gen.edge.v1.SyncCompletedMsg;
import org.thingsboard.server.gen.edge.v1.TenantProfileUpdateMsg;
import org.thingsboard.server.gen.edge.v1.TenantUpdateMsg;
import org.thingsboard.server.gen.edge.v1.UplinkMsg;
import org.thingsboard.server.gen.edge.v1.UpdateMsgType;
import org.thingsboard.server.gen.edge.v1.UserCredentialsUpdateMsg;
import org.thingsboard.server.gen.edge.v1.UserUpdateMsg;
@ -117,6 +119,7 @@ import java.util.Optional;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -138,7 +141,7 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
registry.add("edges.rpc.port", () -> EDGE_PORT);
}
public static final Integer CONNECT_MESSAGE_COUNT = 31;
public static final Integer CONNECT_MESSAGE_COUNT = 29;
public static final Integer INSTALLATION_MESSAGE_COUNT = 6;
public static final Integer SYNC_MESSAGE_COUNT = CONNECT_MESSAGE_COUNT + INSTALLATION_MESSAGE_COUNT;
protected static final String THERMOSTAT_DEVICE_PROFILE_NAME = "Thermostat";
@ -156,6 +159,16 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
private static List<UUID> idsToRemove = new ArrayList<>();
protected void sendUplinkMsgAndWaitForResponse(Consumer<UplinkMsg.Builder> customizer) throws Exception {
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt());
customizer.accept(uplinkMsgBuilder);
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
Assert.assertTrue(edgeImitator.waitForResponses());
}
@Before
public void setupEdgeTest() throws Exception {
loginSysAdmin();
@ -298,9 +311,9 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
validateMsgsCnt(RuleChainMetadataUpdateMsg.class, 1);
validateRuleChainMetadataUpdates(ruleChainUUID);
// 4 messages ('general', 'mail', 'connectivity', 'jwt')
validateMsgsCnt(AdminSettingsUpdateMsg.class, 4);
validateAdminSettings(4);
// 2 messages ('general', 'connectivity')
validateMsgsCnt(AdminSettingsUpdateMsg.class, 2);
validateAdminSettings(2);
// 5 messages
// - 1 from default profile fetcher
@ -467,18 +480,16 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
for (AdminSettingsUpdateMsg adminSettingsUpdateMsg : adminSettingsUpdateMsgs) {
AdminSettings adminSettings = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true);
Assert.assertNotNull(adminSettings);
// Only allow-listed keys sync to the edge; provider/secret settings (e.g. 'mail', 'jwt',
// self-registration mappings) must never arrive on the edge.
Assert.assertTrue("Unexpected admin settings key synced to edge: " + adminSettings.getKey(),
adminSettings.getKey().equals("general") || adminSettings.getKey().equals("connectivity"));
if (adminSettings.getKey().equals("general")) {
validateGeneralAdminSettings(adminSettings);
}
if (adminSettings.getKey().equals("mail")) {
validateMailAdminSettings(adminSettings);
}
if (adminSettings.getKey().equals("connectivity")) {
validateConnectivityAdminSettings(adminSettings);
}
if (adminSettings.getKey().equals("jwt")) {
validateJwtAdminSettings(adminSettings);
}
}
}
@ -486,15 +497,6 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
Assert.assertNotNull(adminSettings.getJsonValue().get("baseUrl"));
}
private void validateMailAdminSettings(AdminSettings adminSettings) {
JsonNode jsonNode = adminSettings.getJsonValue();
Assert.assertNotNull(jsonNode.get("mailFrom"));
Assert.assertNotNull(jsonNode.get("smtpProtocol"));
Assert.assertNotNull(jsonNode.get("smtpHost"));
Assert.assertNotNull(jsonNode.get("smtpPort"));
Assert.assertNotNull(jsonNode.get("timeout"));
}
private void validateConnectivityAdminSettings(AdminSettings adminSettings) {
JsonNode jsonNode = adminSettings.getJsonValue();
Assert.assertNotNull(jsonNode.get("http"));

109
application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java

@ -1,109 +0,0 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.edge;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.AbstractMessage;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg;
@DaoSqlTest
public class AdminSettingsEdgeTest extends AbstractEdgeTest {
@Autowired
private AdminSettingsService adminSettingsService;
@Test
public void testAdminSettings_sysAdmin() throws Exception {
loginSysAdmin();
AdminSettings adminSettings = new AdminSettings();
adminSettings.setKey("edgeTest");
ObjectNode jsonValue = JacksonUtil.newObjectNode();
jsonValue.put("key1", "value1");
adminSettings.setJsonValue(jsonValue);
edgeImitator.expectMessageAmount(1);
AdminSettings savedAdminSettings = doPost("/api/admin/settings", adminSettings, AdminSettings.class);
Assert.assertTrue(edgeImitator.waitForMessages());
AbstractMessage latestMessage = edgeImitator.getLatestMessage();
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg);
AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage;
AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true);
Assert.assertNotNull(adminSettingsMsg);
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey());
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText());
ObjectNode updatedJsonValue = (ObjectNode) savedAdminSettings.getJsonValue();
updatedJsonValue.put("key2", "value2");
savedAdminSettings.setJsonValue(updatedJsonValue);
edgeImitator.expectMessageAmount(1);
doPost("/api/admin/settings", savedAdminSettings, AdminSettings.class);
Assert.assertTrue(edgeImitator.waitForMessages());
latestMessage = edgeImitator.getLatestMessage();
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg);
adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage;
adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true);
Assert.assertNotNull(adminSettingsMsg);
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey());
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText());
Assert.assertEquals("value2", adminSettingsMsg.getJsonValue().get("key2").asText());
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedAdminSettings.getTenantId(), "edgeTest");
}
@Test
public void testAdminSettings_tenant() throws Exception {
loginTenantAdmin();
AdminSettings tenantAdminSettings = new AdminSettings();
tenantAdminSettings.setTenantId(tenantId);
tenantAdminSettings.setKey("tenantEdgeTest");
ObjectNode tenantJsonValue = JacksonUtil.newObjectNode();
tenantJsonValue.put("tenantKey1", "tenantValue1");
tenantAdminSettings.setJsonValue(tenantJsonValue);
edgeImitator.expectMessageAmount(1);
AdminSettings savedTenantAdminSettings = doPost("/api/admin/settings", tenantAdminSettings, AdminSettings.class);
Assert.assertTrue(edgeImitator.waitForMessages());
AbstractMessage latestMessage = edgeImitator.getLatestMessage();
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg);
AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage;
AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true);
Assert.assertNotNull(adminSettingsMsg);
Assert.assertEquals("tenantEdgeTest", adminSettingsMsg.getKey());
Assert.assertEquals("tenantValue1", adminSettingsMsg.getJsonValue().get("tenantKey1").asText());
// TENANT update
ObjectNode updatedTenantJsonValue = (ObjectNode) savedTenantAdminSettings.getJsonValue();
updatedTenantJsonValue.put("tenantKey2", "tenantValue2");
savedTenantAdminSettings.setJsonValue(updatedTenantJsonValue);
edgeImitator.expectMessageAmount(1);
doPost("/api/admin/settings", savedTenantAdminSettings, AdminSettings.class);
Assert.assertTrue(edgeImitator.waitForMessages());
latestMessage = edgeImitator.getLatestMessage();
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg);
adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage;
adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true);
Assert.assertNotNull(adminSettingsMsg);
Assert.assertEquals("tenantEdgeTest", adminSettingsMsg.getKey());
Assert.assertEquals("tenantValue1", adminSettingsMsg.getJsonValue().get("tenantKey1").asText());
Assert.assertEquals("tenantValue2", adminSettingsMsg.getJsonValue().get("tenantKey2").asText());
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedTenantAdminSettings.getTenantId(), "tenantEdgeTest");
}
}

198
application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java

@ -0,0 +1,198 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.edge;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.rule.engine.api.TbEmail;
import org.thingsboard.server.common.data.ApiFeature;
import org.thingsboard.server.common.data.ApiUsageStateValue;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg;
import org.thingsboard.server.service.mail.EdgeMailRequest;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
/**
* Verifies the send-email uplink: when the Edge delegates a mail send, the Cloud receives the
* SendEmailUplinkMsg and invokes its MailService (which resolves the config, renders and transmits). Here
* the EdgeImitator plays the Edge and sends the uplink; the Cloud's MailService is mocked so we can assert
* the delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of
* the connected edge).
*/
@DaoSqlTest
public class SendEmailEdgeTest extends AbstractEdgeTest {
@MockitoBean
private MailService mailService;
@Test
public void testSendBasicEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.SEND_BASIC)
.to("recipient@thingsboard.io")
.subject("Edge test subject")
.message("<b>Edge test body</b>")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("<b>Edge test body</b>"));
}
@Test
public void testSendTbEmailFromEdgeProcessedByCloud() throws Exception {
TbEmail tbEmail = TbEmail.builder()
.from("noreply@thingsboard.io")
.to("recipient@thingsboard.io")
.subject("Rule chain email")
.body("Alarm!")
.html(false)
.build();
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.SEND_TB_EMAIL)
.tbEmail(tbEmail)
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class));
}
@Test
public void testSendActivationEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.ACTIVATION)
.activationLink("http://localhost/activate?token=abc")
.ttlMs(60000L)
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendActivationEmail(eq(tenantId), eq("http://localhost/activate?token=abc"), eq(60000L), eq("recipient@thingsboard.io"));
}
@Test
public void testSendAccountActivatedEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.ACCOUNT_ACTIVATED)
.loginLink("http://localhost/login")
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendAccountActivatedEmail(eq(tenantId), eq("http://localhost/login"), eq("recipient@thingsboard.io"));
}
@Test
public void testSendResetPasswordEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.RESET_PASSWORD)
.passwordResetLink("http://localhost/reset?token=abc")
.ttlMs(60000L)
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendResetPasswordEmail(eq(tenantId), eq("http://localhost/reset?token=abc"), eq(60000L), eq("recipient@thingsboard.io"));
}
@Test
public void testSendPasswordWasResetEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.PASSWORD_WAS_RESET)
.loginLink("http://localhost/login")
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendPasswordWasResetEmail(eq(tenantId), eq("http://localhost/login"), eq("recipient@thingsboard.io"));
}
@Test
public void testSendTwoFaVerificationEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.TWO_FA)
.to("recipient@thingsboard.io")
.verificationCode("123456")
.expirationTimeSeconds(120)
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendTwoFaVerificationEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("123456"), eq(120));
}
@Test
public void testSendAccountLockoutEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.ACCOUNT_LOCKOUT)
.lockoutEmail("locked@thingsboard.io")
.to("recipient@thingsboard.io")
.maxFailedLoginAttempts(5)
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendAccountLockoutEmail(eq(tenantId), eq("locked@thingsboard.io"), eq("recipient@thingsboard.io"), eq(5));
}
@Test
public void testSendApiUsageStateEmailFromEdgeProcessedByCloud() throws Exception {
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.API_USAGE_STATE)
.apiFeature(ApiFeature.EMAIL)
.stateValue(ApiUsageStateValue.DISABLED)
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendApiFeatureStateEmail(eq(tenantId), eq(ApiFeature.EMAIL), eq(ApiUsageStateValue.DISABLED), eq("recipient@thingsboard.io"), isNull());
}
@Test
public void testSendTestMailFromEdgeProcessedByCloud() throws Exception {
JsonNode testConfig = JacksonUtil.newObjectNode().put("smtpHost", "localhost");
EdgeMailRequest request = EdgeMailRequest.builder()
.method(EdgeMailRequest.MailMethod.TEST_MAIL)
.testConfig(testConfig)
.to("recipient@thingsboard.io")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendTestMail(eq(tenantId), any(JsonNode.class), eq("recipient@thingsboard.io"));
}
private void sendEmailUplink(EdgeMailRequest request) throws Exception {
SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequest(JacksonUtil.toString(request))
.build();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendEmailUplinkMsg(sendEmailUplinkMsg));
}
}

106
application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java

@ -0,0 +1,106 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.edge;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.notification.FirebaseService;
import org.thingsboard.rule.engine.api.notification.SlackService;
import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod;
import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.settings.NotificationSettings;
import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig;
import org.thingsboard.server.dao.notification.NotificationSettingsService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg;
import org.thingsboard.server.service.notification.EdgeNotificationRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
/**
* Verifies the send-notification uplink: when the Edge delegates a Slack or mobile-push notification, the
* Cloud receives the SendNotificationUplinkMsg, resolves the channel credentials from its own notification
* settings and delivers. The EdgeImitator plays the Edge and sends the uplink; the Cloud's SlackService and
* FirebaseService are mocked so we can assert the delegated call arrives with the expected arguments.
*/
@DaoSqlTest
public class SendNotificationEdgeTest extends AbstractEdgeTest {
@MockitoBean
private SlackService slackService;
@MockitoBean
private FirebaseService firebaseService;
@Autowired
private NotificationSettingsService notificationSettingsService;
private void prepareNotificationSettings() {
SlackNotificationDeliveryMethodConfig slack = new SlackNotificationDeliveryMethodConfig();
slack.setBotToken("xoxb-edge-test-token");
MobileAppNotificationDeliveryMethodConfig mobile = new MobileAppNotificationDeliveryMethodConfig();
mobile.setUseSystemSettings(false);
mobile.setFirebaseServiceAccountCredentials("{\"type\":\"service_account\"}");
NotificationSettings settings = new NotificationSettings();
Map<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> configs = new HashMap<>();
configs.put(NotificationDeliveryMethod.SLACK, slack);
configs.put(NotificationDeliveryMethod.MOBILE_APP, mobile);
settings.setDeliveryMethodsConfigs(configs);
notificationSettingsService.saveNotificationSettings(tenantId, settings);
}
@Test
public void testSendSlackNotificationFromEdgeProcessedByCloud() throws Exception {
prepareNotificationSettings();
EdgeNotificationRequest request = EdgeNotificationRequest.builder()
.method(EdgeNotificationRequest.NotificationMethod.SEND_SLACK)
.conversationId("C0123456789")
.message("Edge Slack notification")
.build();
sendNotificationUplink(request);
verify(slackService, timeout(30000))
.sendMessage(eq(tenantId), anyString(), eq("C0123456789"), eq("Edge Slack notification"), any());
}
@Test
public void testSendMobilePushFromEdgeProcessedByCloud() throws Exception {
prepareNotificationSettings();
EdgeNotificationRequest request = EdgeNotificationRequest.builder()
.method(EdgeNotificationRequest.NotificationMethod.SEND_MOBILE_PUSH)
.fcmTokens(Set.of("fcm-token-1"))
.subject("Edge subject")
.body("Edge body")
.badge(3)
.build();
sendNotificationUplink(request);
verify(firebaseService, timeout(30000))
.sendMessage(eq(tenantId), anyString(), eq("fcm-token-1"), eq("Edge subject"), eq("Edge body"), any(), eq(3));
}
private void sendNotificationUplink(EdgeNotificationRequest request) throws Exception {
SendNotificationUplinkMsg sendNotificationUplinkMsg = SendNotificationUplinkMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequest(JacksonUtil.toString(request))
.build();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg));
}
}

72
application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java

@ -0,0 +1,72 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.edge;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.SmsService;
import org.thingsboard.server.common.data.sms.config.TestSmsRequest;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg;
import org.thingsboard.server.service.sms.EdgeSmsRequest;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
/**
* Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the
* SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the
* EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the
* delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the
* connected edge).
*/
@DaoSqlTest
public class SendSmsEdgeTest extends AbstractEdgeTest {
@MockitoBean
private SmsService smsService;
@Test
public void testSendSmsFromEdgeProcessedByCloud() throws Exception {
EdgeSmsRequest request = EdgeSmsRequest.builder()
.method(EdgeSmsRequest.SmsMethod.SEND_SMS)
.numbers(new String[]{"+15551234567"})
.message("Edge test message")
.build();
sendSmsUplink(request);
verify(smsService, timeout(30000))
.sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message"));
}
@Test
public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception {
TestSmsRequest testSmsRequest = new TestSmsRequest();
testSmsRequest.setNumberTo("+15551234567");
testSmsRequest.setMessage("Test message");
EdgeSmsRequest request = EdgeSmsRequest.builder()
.method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS)
.testSmsRequest(testSmsRequest)
.build();
sendSmsUplink(request);
verify(smsService, timeout(30000)).sendTestSms(eq(tenantId), any(TestSmsRequest.class));
}
private void sendSmsUplink(EdgeSmsRequest request) throws Exception {
SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequest(JacksonUtil.toString(request))
.build();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendSmsUplinkMsg(sendSmsUplinkMsg));
}
}

74
application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java

@ -20,11 +20,13 @@ import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserCredentialsId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.gen.edge.v1.UpdateMsgType;
import org.thingsboard.server.gen.edge.v1.UplinkMsg;
import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg;
@ -48,6 +50,9 @@ public class UserEdgeTest extends AbstractEdgeTest {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserService userService;
private static final String DEFAULT_FIRST_NAME = "Boris";
private static final String DEFAULT_LAST_NAME = "Johnson";
private static final String UPDATED_LAST_NAME = "Borisov";
@ -393,6 +398,75 @@ public class UserEdgeTest extends AbstractEdgeTest {
Assert.assertEquals(savedTenantAdmin.getUuidId().getLeastSignificantBits(), userUpdateMsg.getIdLSB());
}
@Test
public void testSendUserWithUnsupportedAuthorityFromEdgeToCloud() throws Exception {
UserId userId = new UserId(UUID.randomUUID());
User sysAdmin = buildUser(Authority.SYS_ADMIN, null);
sysAdmin.setId(userId);
sysAdmin.setTenantId(TenantId.SYS_TENANT_ID);
UserCredentials userCredentials = buildCredentials(new UserCredentialsId(UUID.randomUUID()), userId, true);
userCredentials.setPassword(passwordEncoder.encode("password"));
sendUplinkMsg(UplinkMsg.newBuilder()
.addUserUpdateMsg(EdgeMsgConstructorUtils.constructUserUpdatedMsg(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, sysAdmin, null))
.addUserCredentialsUpdateMsg(EdgeMsgConstructorUtils.constructUserCredentialsUpdatedMsg(userCredentials))
.build());
Assert.assertNull(userService.findUserById(TenantId.SYS_TENANT_ID, userId));
}
@Test
public void testSendUserWithDifferentTenantIdFromEdgeToCloud() throws Exception {
UserId userId = new UserId(UUID.randomUUID());
User tenantAdmin = buildUser(Authority.TENANT_ADMIN, null);
tenantAdmin.setId(userId);
tenantAdmin.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
UserCredentials userCredentials = buildCredentials(new UserCredentialsId(UUID.randomUUID()), userId, false);
sendUplinkMsg(UplinkMsg.newBuilder()
.addUserUpdateMsg(EdgeMsgConstructorUtils.constructUserUpdatedMsg(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, tenantAdmin, null))
.addUserCredentialsUpdateMsg(EdgeMsgConstructorUtils.constructUserCredentialsUpdatedMsg(userCredentials))
.build());
User userFromCloud = doGet("/api/user/" + userId, User.class);
Assert.assertEquals(tenantId, userFromCloud.getTenantId());
}
@Test
public void testSendUserMsgsForUserOfAnotherTenantFromEdgeToCloud() throws Exception {
User sysAdmin = userService.findUserByEmail(TenantId.SYS_TENANT_ID, SYS_ADMIN_EMAIL);
UserCredentials sysAdminCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, sysAdmin.getId());
// update, credentials update and delete for a user outside of edge's tenant
User tenantAdmin = buildUser(Authority.TENANT_ADMIN, null);
tenantAdmin.setId(sysAdmin.getId());
UserCredentials userCredentials = buildCredentials(new UserCredentialsId(UUID.randomUUID()), sysAdmin.getId(), true);
userCredentials.setPassword(passwordEncoder.encode("password"));
sendUplinkMsg(UplinkMsg.newBuilder()
.addUserUpdateMsg(EdgeMsgConstructorUtils.constructUserUpdatedMsg(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE, tenantAdmin, null))
.build());
sendUplinkMsg(UplinkMsg.newBuilder()
.addUserCredentialsUpdateMsg(EdgeMsgConstructorUtils.constructUserCredentialsUpdatedMsg(userCredentials))
.build());
sendUplinkMsg(UplinkMsg.newBuilder()
.addUserUpdateMsg(EdgeMsgConstructorUtils.constructUserDeleteMsg(sysAdmin.getId(), null))
.build());
User sysAdminAfter = userService.findUserById(TenantId.SYS_TENANT_ID, sysAdmin.getId());
Assert.assertNotNull(sysAdminAfter);
Assert.assertEquals(Authority.SYS_ADMIN, sysAdminAfter.getAuthority());
Assert.assertEquals(TenantId.SYS_TENANT_ID, sysAdminAfter.getTenantId());
UserCredentials sysAdminCredentialsAfter = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, sysAdmin.getId());
Assert.assertEquals(sysAdminCredentials.getId(), sysAdminCredentialsAfter.getId());
Assert.assertEquals(sysAdminCredentials.getPassword(), sysAdminCredentialsAfter.getPassword());
}
private void sendUplinkMsg(UplinkMsg uplinkMsg) throws Exception {
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsg);
Assert.assertTrue(edgeImitator.waitForResponses());
}
private UplinkMsg buildUserUplinkMsg(UserId userId, CustomerId customerId, UserCredentialsId userCredentialsUuid, EntityGroupId entityGroupId) {
User customerUser = buildUser(Authority.CUSTOMER_USER, customerId);
customerUser.setId(userId);

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

@ -33,18 +33,21 @@ import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
import org.thingsboard.server.service.ai.transport.TbAiChannelUnavailableException;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@ -493,6 +496,54 @@ class DefaultTbAiServiceTest {
new TbAiSettings(enabled, sseInactivityTimeoutSeconds, sseLogMaxDataLength), operations);
}
@Test
void shouldTellTheTurnTheBrowserLeft_andStillReportCredits_whenClientCancelsMidStream() {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
upstream = Sinks.many().unicast().onBackpressureBuffer();
AtomicBoolean left = new AtomicBoolean();
TbAiTurnLink link = new TbAiTurnLink();
link.onClientLeft(() -> left.set(true));
Disposable client = service.processStream(chatId, tokenProvider -> upstream.asFlux(), user, link, true).subscribe();
upstream.tryEmitNext(assistantMessage("hello"));
// WHEN
client.dispose();
upstream.tryEmitNext(creditsUsedEvent(150));
upstream.tryEmitComplete();
// THEN
assertThat(left).isTrue();
then(apiUsageReportClient).should().report(tenantId, customerId, ApiUsageRecordKey.AI_CREDITS_COUNT, 150L);
}
@Test
void shouldNotTellTheTurnTheBrowserLeft_whenTheStreamEnds() {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
AtomicBoolean left = new AtomicBoolean();
TbAiTurnLink link = new TbAiTurnLink();
link.onClientLeft(() -> left.set(true));
// WHEN
service.processStream(chatId, tokenProvider -> Flux.just(assistantMessage("hello")), user, link, true)
.collectList().block(Duration.ofSeconds(5));
// THEN
assertThat(left).isFalse();
}
@Test
void shouldFollowTheTurnWithoutLookingAtCredits_whenCreditsAreNotChecked() {
// WHEN
List<ServerSentEvent<String>> events = service.processStream(chatId, tokenProvider -> Flux.just(assistantMessage("hello")), user,
new TbAiTurnLink(), false).collectList().block(Duration.ofSeconds(5));
// THEN
assertThat(events).extracting(ServerSentEvent::event).containsExactly("assistantMessage");
then(apiUsageStateService).shouldHaveNoInteractions();
}
private SecurityUser newUser(TenantId tenant) {
SecurityUser u = new SecurityUser();
u.setId(userId);

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

@ -20,6 +20,7 @@ import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -133,7 +134,8 @@ class DefaultAiChatServiceTest {
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
&& Objects.equals(new ChatOperationRequest(chatId, JacksonUtil.newObjectNode().put("toolCards", true)), operation.payload())),
same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -164,10 +166,10 @@ class DefaultAiChatServiceTest {
.event("assistantMessage")
.data("{\"message\":\"ok\"}")
.build());
given(tbAiService.processStream(eq(chatId), any(), same(user))).willReturn(expectedStream);
given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream);
var clientOrigin = "https://tb.example.com";
var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
given(tbAiTransport.sendChatMessage(eq(chatId), same(request), eq(expectedContext))).willReturn(expectedStream);
given(tbAiTransport.sendChatMessage(eq(chatId), same(request), eq(expectedContext), any(TbAiTurnLink.class))).willReturn(expectedStream);
// WHEN
Flux<ServerSentEvent<String>> result = service.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, clientOrigin, user);
@ -175,8 +177,35 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedStream);
assertThat(captureProcessStreamCall(chatId).apply(tokenProvider)).isSameAs(expectedStream);
then(tbAiTransport).should().sendChatMessage(eq(chatId), same(request), eq(expectedContext));
ProcessStreamCall call = captureProcessStreamCall(chatId, true);
assertThat(call.action().apply(tokenProvider)).isSameAs(expectedStream);
then(tbAiTransport).should().sendChatMessage(eq(chatId), same(request), eq(expectedContext), same(call.link()));
then(tbAiTransport).shouldHaveNoMoreInteractions();
then(tbAiService).shouldHaveNoMoreInteractions();
}
@Test
void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() {
// GIVEN
UUID chatId = UUID.randomUUID();
Flux<ServerSentEvent<String>> expectedStream = Flux.just(ServerSentEvent.<String>builder()
.event("turnResumed")
.data("{}")
.build());
given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(false))).willReturn(expectedStream);
var clientOrigin = "https://tb.example.com";
var expectedContext = new TbAiTurnContext(user, "tb-access-token", "en-US", tokenProvider, clientOrigin);
given(tbAiTransport.resumeChat(eq(chatId), eq(expectedContext), any(TbAiTurnLink.class))).willReturn(expectedStream);
// WHEN
Flux<ServerSentEvent<String>> result = service.resumeChat(chatId, "tb-access-token", "en-US", clientOrigin, user);
// THEN
assertThat(result).isSameAs(expectedStream);
ProcessStreamCall call = captureProcessStreamCall(chatId, false);
assertThat(call.action().apply(tokenProvider)).isSameAs(expectedStream);
then(tbAiTransport).should().resumeChat(eq(chatId), eq(expectedContext), same(call.link()));
then(tbAiTransport).shouldHaveNoMoreInteractions();
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -188,11 +217,14 @@ class DefaultAiChatServiceTest {
return callCaptor.getValue();
}
private record ProcessStreamCall(TbAiService.TbAiCall<Flux<ServerSentEvent<String>>> action, TbAiTurnLink link) {}
@SuppressWarnings({"rawtypes", "unchecked"})
private TbAiService.TbAiCall<Flux<ServerSentEvent<String>>> captureProcessStreamCall(UUID chatId) {
private ProcessStreamCall captureProcessStreamCall(UUID chatId, boolean checkCredits) {
ArgumentCaptor<TbAiService.TbAiCall> callCaptor = ArgumentCaptor.forClass(TbAiService.TbAiCall.class);
then(tbAiService).should().processStream(eq(chatId), callCaptor.capture(), same(user));
return callCaptor.getValue();
ArgumentCaptor<TbAiTurnLink> linkCaptor = ArgumentCaptor.forClass(TbAiTurnLink.class);
then(tbAiService).should().processStream(eq(chatId), callCaptor.capture(), same(user), linkCaptor.capture(), eq(checkCredits));
return new ProcessStreamCall(callCaptor.getValue(), linkCaptor.getValue());
}
private static ObjectNode createChatRequest(String title) {

95
application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java

@ -118,7 +118,7 @@ class ChannelTbAiTransportTest {
AtomicBoolean heartbeat = new AtomicBoolean();
// WHEN
Disposable subscription = transport.sendChatMessage(UUID.randomUUID(), request, context).subscribe(event -> heartbeat.set(true));
Disposable subscription = transport.sendChatMessage(UUID.randomUUID(), request, context, null).subscribe(event -> heartbeat.set(true));
await().atMost(Duration.ofSeconds(5)).untilTrue(heartbeat);
subscription.dispose();
@ -129,6 +129,97 @@ class ChannelTbAiTransportTest {
assertThat(server.openConnections.get()).isEqualTo(1);
}
@Test
void shouldDetachButKeepListening_whenBrowserLeavesAndServerCanResumeTurns() {
// GIVEN
server = FakeTbAiServer.start(List.of(ChannelProtocol.TURN_RESUME_CAPABILITY), (connection, frame) -> {
if (ChannelProtocol.CHAT_SEND.equals(frame.type())) {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("heartbeat", null));
}
});
pool = pool();
var transport = new ChannelTbAiTransport(pool, requestExecutor);
var link = new TbAiTurnLink();
AtomicBoolean heartbeat = new AtomicBoolean();
transport.sendChatMessage(UUID.randomUUID(), request, context, link).subscribe(event -> heartbeat.set(true));
await().atMost(Duration.ofSeconds(5)).untilTrue(heartbeat);
// WHEN
link.clientLeft();
// THEN
await().atMost(Duration.ofSeconds(5)).until(() -> !server.received(ChannelProtocol.CHAT_DETACH).isEmpty());
assertThat(server.received(ChannelProtocol.CHAT_DETACH).getFirst().op())
.isEqualTo(server.received(ChannelProtocol.CHAT_SEND).getFirst().id());
assertThat(server.received(ChannelProtocol.CANCEL)).isEmpty();
}
@Test
void shouldNotSendDetach_whenServerCannotResumeTurns() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> {
if (ChannelProtocol.CHAT_SEND.equals(frame.type())) {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("heartbeat", null));
}
});
pool = pool();
var transport = new ChannelTbAiTransport(pool, requestExecutor);
var link = new TbAiTurnLink();
AtomicBoolean heartbeat = new AtomicBoolean();
transport.sendChatMessage(UUID.randomUUID(), request, context, link).subscribe(event -> heartbeat.set(true));
await().atMost(Duration.ofSeconds(5)).untilTrue(heartbeat);
// WHEN
link.clientLeft();
transport.sendChatMessage(UUID.randomUUID(), request, context, null).subscribe();
// THEN
await().atMost(Duration.ofSeconds(5)).until(() -> server.received(ChannelProtocol.CHAT_SEND).size() == 2);
assertThat(server.received(ChannelProtocol.CHAT_DETACH)).isEmpty();
assertThat(server.openConnections.get()).isEqualTo(1);
}
@Test
void shouldRelayTheResumedTurn_whenServerCanResumeTurns() {
// GIVEN
UUID chatId = UUID.randomUUID();
server = FakeTbAiServer.start(List.of(ChannelProtocol.TURN_RESUME_CAPABILITY), (connection, frame) -> {
if (ChannelProtocol.CHAT_RESUME.equals(frame.type())) {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("turnResumed", JacksonUtil.newObjectNode()));
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("assistantMessage",
JacksonUtil.newObjectNode().put("message", "Done.")));
connection.sendFor(frame, ChannelProtocol.TURN_END, new TurnEnd(TurnEnd.Status.COMPLETED));
}
});
pool = pool();
// WHEN
List<ServerSentEvent<String>> events = new ChannelTbAiTransport(pool, requestExecutor)
.resumeChat(chatId, context, new TbAiTurnLink())
.collectList().block(Duration.ofSeconds(10));
// THEN
assertThat(events).extracting(ServerSentEvent::event).containsExactly("turnResumed", "assistantMessage");
ChatTurnRequest resume = server.codec.fromPayload(server.received(ChannelProtocol.CHAT_RESUME).getFirst().payload(), ChatTurnRequest.class);
assertThat(resume).isEqualTo(new ChatTurnRequest(chatId, null, context.acceptLanguage()));
}
@Test
void shouldEndAtOnceWithoutAsking_whenServerCannotResumeTurns() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> {});
pool = pool();
// WHEN
List<ServerSentEvent<String>> events = new ChannelTbAiTransport(pool, requestExecutor)
.resumeChat(UUID.randomUUID(), context, new TbAiTurnLink())
.collectList().block(Duration.ofSeconds(10));
// THEN
assertThat(events).isEmpty();
assertThat(server.received(ChannelProtocol.CHAT_RESUME)).isEmpty();
}
@Test
void shouldSignalChannelUnavailable_whenServerHasNoChannelEndpoint() {
// GIVEN
@ -159,7 +250,7 @@ class ChannelTbAiTransportTest {
TbAiTurnContext turnContext = new TbAiTurnContext(context.tenantId(), context.userId(), context.user(), "Bearer user-jwt",
"de-DE", context.tokenProvider(), "https://tb.example.com");
return new ChannelTbAiTransport(pool, requestExecutor)
.sendChatMessage(UUID.randomUUID(), request, turnContext)
.sendChatMessage(UUID.randomUUID(), request, turnContext, null)
.collectList()
.block(Duration.ofSeconds(10));
}

10
application/src/test/java/org/thingsboard/server/service/ai/transport/FakeTbAiServer.java

@ -38,7 +38,7 @@ class FakeTbAiServer implements AutoCloseable {
final AtomicInteger openConnections = new AtomicInteger();
private final DisposableServer server;
private FakeTbAiServer(Script script) {
private FakeTbAiServer(List<String> capabilities, Script script) {
server = HttpServer.create().host("127.0.0.1").port(0)
.route(routes -> routes.ws(ChannelProtocol.WS_PATH, (inbound, outbound) -> {
connections.incrementAndGet();
@ -49,7 +49,7 @@ class FakeTbAiServer implements AutoCloseable {
received.add(frame);
if (ChannelProtocol.HELLO.equals(frame.type())) {
connection.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(
new ChannelHello(1, null, null, (long) TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES))));
new ChannelHello(1, capabilities, null, (long) TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES))));
} else {
script.onFrame(connection, frame);
}
@ -63,7 +63,11 @@ class FakeTbAiServer implements AutoCloseable {
}
static FakeTbAiServer start(Script script) {
return new FakeTbAiServer(script);
return new FakeTbAiServer(null, script);
}
static FakeTbAiServer start(List<String> capabilities, Script script) {
return new FakeTbAiServer(capabilities, script);
}
static FakeTbAiServer rejecting(int status) {

112
application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java

@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.edge.rpc.processor.settings;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.edge.EdgeEvent;
import org.thingsboard.server.common.data.id.AdminSettingsId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import org.thingsboard.server.gen.edge.v1.DownlinkMsg;
import org.thingsboard.server.gen.edge.v1.EdgeVersion;
import org.thingsboard.server.service.edge.EdgeContextComponent;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class AdminSettingsEdgeProcessorTest {
@Mock
private EdgeContextComponent edgeCtx;
@Mock
private AdminSettingsService adminSettingsService;
private final TenantId tenantId = new TenantId(UUID.randomUUID());
private AdminSettingsEdgeProcessor processor;
@BeforeEach
public void setUp() {
processor = new AdminSettingsEdgeProcessor();
ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx);
lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService);
}
@Test
public void testTenantScopedAllowListedKeyIsSyncedToEdge() {
AdminSettings general = adminSettings(tenantId, "general");
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general);
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4);
Assertions.assertNotNull(downlink);
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount());
AdminSettings synced = JacksonUtil.fromString(downlink.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true);
Assertions.assertNotNull(synced);
Assertions.assertEquals("general", synced.getKey());
}
@Test
public void testTenantScopedNonAllowListedKeyIsNotSyncedToEdge() {
AdminSettings mail = adminSettings(tenantId, "mail");
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(mail);
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4);
Assertions.assertNull(downlink);
}
@Test
public void testSystemScopedAllowListedKeyIsSyncedToEdge() {
AdminSettings connectivity = adminSettings(TenantId.SYS_TENANT_ID, "connectivity");
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(connectivity);
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4);
Assertions.assertNotNull(downlink);
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount());
}
@ParameterizedTest
@ValueSource(strings = {"mail", "jwt", "sms", "notifications"})
public void testSystemScopedNonAllowListedKeyIsNotSyncedToEdge(String key) {
AdminSettings settings = adminSettings(TenantId.SYS_TENANT_ID, key);
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(settings);
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4);
Assertions.assertNull(downlink);
}
private EdgeEvent edgeEvent(TenantId eventTenantId) {
EdgeEvent edgeEvent = new EdgeEvent();
edgeEvent.setTenantId(eventTenantId);
edgeEvent.setEdgeId(new EdgeId(UUID.randomUUID()));
edgeEvent.setEntityId(UUID.randomUUID());
return edgeEvent;
}
private AdminSettings adminSettings(TenantId settingsTenantId, String key) {
AdminSettings adminSettings = new AdminSettings();
adminSettings.setId(new AdminSettingsId(UUID.randomUUID()));
adminSettings.setTenantId(settingsTenantId);
adminSettings.setKey(key);
adminSettings.setJsonValue(JacksonUtil.newObjectNode());
return adminSettings;
}
}

40
application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/wl/WhiteLabelingEdgeProcessorTest.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.edge.rpc.processor.wl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.wl.WhiteLabelingType;
import java.util.UUID;
public class WhiteLabelingEdgeProcessorTest {
private final WhiteLabelingEdgeProcessor processor = new WhiteLabelingEdgeProcessor();
private final TenantId tenantId = new TenantId(UUID.randomUUID());
@Test
public void testSystemMailTemplatesAreNotSyncedToEdge() {
// System mail templates are rendered on the cloud, so they must never be pushed to the edge.
Assertions.assertTrue(isSystemMailTemplates(WhiteLabelingType.MAIL_TEMPLATES, TenantId.SYS_TENANT_ID));
}
@Test
public void testTenantMailTemplatesAreStillSyncedToEdge() {
// Only system-scoped mail templates are skipped; tenant-scoped ones keep syncing.
Assertions.assertFalse(isSystemMailTemplates(WhiteLabelingType.MAIL_TEMPLATES, tenantId));
}
@Test
public void testSystemNonMailTemplatesAreStillSyncedToEdge() {
// Other system white-labeling (e.g. GENERAL) is not affected by the mail-templates skip.
Assertions.assertFalse(isSystemMailTemplates(WhiteLabelingType.GENERAL, TenantId.SYS_TENANT_ID));
}
private boolean isSystemMailTemplates(WhiteLabelingType type, TenantId tenantId) {
return Boolean.TRUE.equals(ReflectionTestUtils.invokeMethod(processor, "isSystemMailTemplates", type, tenantId));
}
}

250
application/src/test/java/org/thingsboard/server/service/edge/rpc/service/EdgeGrpcServiceTest.java

@ -0,0 +1,250 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.edge.rpc.service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatcher;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger;
import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.service.edge.EdgeContextComponent;
import org.thingsboard.server.service.edge.rpc.EdgeSessionState;
import org.thingsboard.server.service.edge.rpc.session.EdgeSessionsHolder;
import org.thingsboard.server.service.edge.rpc.session.manager.EdgeGrpcSessionManager;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_DISCONNECT_TIME;
@ExtendWith(MockitoExtension.class)
class EdgeGrpcServiceTest {
private static final String THIS_NODE = "tb-core-1";
private static final String OTHER_NODE = "tb-core-2";
@Mock
private ApplicationContext applicationContext;
@Mock
private TbClusterService clusterService;
@Mock
private TbServiceInfoProvider serviceInfoProvider;
@Mock
private TelemetrySubscriptionService tsSubService;
@Mock
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache;
@Mock
private PartitionService partitionService;
@Mock
private EdgeContextComponent ctx;
@Mock
private NotificationRuleProcessor ruleProcessor;
private EdgeSessionsHolder sessions;
private EdgeGrpcService edgeGrpcService;
private Edge edge;
private EdgeId edgeId;
@BeforeEach
void setUp() {
sessions = new EdgeSessionsHolder();
edgeGrpcService = new EdgeGrpcService(sessions, applicationContext, clusterService, serviceInfoProvider,
tsSubService, edgeIdServiceIdCache, partitionService);
ReflectionTestUtils.setField(edgeGrpcService, "ctx", ctx);
edgeId = new EdgeId(UUID.randomUUID());
edge = new Edge(edgeId);
edge.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
edge.setName("test-edge");
lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
}
@Test
void givenNoCacheEntry_whenDisconnect_thenAllDisconnectSideEffectsRun() {
EdgeGrpcSessionManager session = registerSession();
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null);
onEdgeDisconnect(session);
verify(tsSubService, times(1)).saveAttributes(argThat(activeStateWrite(false)));
verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite()));
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
verify(ruleProcessor, times(1)).process(argThat(disconnectTrigger()));
}
@Test
void givenEdgeOwnedByAnotherLiveNode_whenDisconnect_thenNoDisconnectSideEffects() {
EdgeGrpcSessionManager session = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE));
onEdgeDisconnect(session);
verifyNoDisconnectSideEffects();
}
@Test
void givenOwnerNodeLeftCluster_whenDisconnect_thenInactiveStateIsPersisted() {
// the cache has no TTL by default, so a dead owner's claim must not keep the edge active forever
EdgeGrpcSessionManager session = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE));
onEdgeDisconnect(session);
verify(tsSubService, times(1)).saveAttributes(argThat(activeStateWrite(false)));
}
@Test
void givenSameNodeReconnectDuringOwnershipCheck_whenDisconnect_thenNoDisconnectSideEffects() {
// the edge reconnects to this node after the stale session was removed, so the cache names this node
EdgeGrpcSessionManager session = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenAnswer(invocation -> {
sessions.put(newSession());
return SimpleTbCacheValueWrapper.wrap(THIS_NODE);
});
onEdgeDisconnect(session);
verifyNoDisconnectSideEffects();
}
@Test
void givenReconnectDuringInactiveWrite_whenDisconnect_thenReconnectWaitsForTheWrite() throws Exception {
// a same-node reconnect racing the guard must be ordered after the inactive write, so its active=true wins
EdgeGrpcSessionManager session = registerSession();
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null);
EdgeGrpcSessionManager replacement = newSession();
Thread reconnect = new Thread(() -> sessions.put(replacement));
AtomicBoolean reconnectBlockedDuringWrite = new AtomicBoolean();
lenient().doAnswer(invocation -> {
reconnect.start();
reconnect.join(200);
reconnectBlockedDuringWrite.set(reconnect.isAlive());
return null;
}).when(tsSubService).saveAttributes(argThat(activeStateWrite(false)));
onEdgeDisconnect(session);
reconnect.join(5000);
assertThat(reconnectBlockedDuringWrite).isTrue();
assertThat(sessions.getByEdgeId(edgeId)).isSameAs(replacement);
}
@Test
void givenReplacedSessionDisconnectsDuringItsTeardown_whenConnect_thenNoDisconnectSideEffects() {
// the edge reconnects before its old stream is noticed dead; the old session's close fires while it is destroyed
EdgeGrpcSessionManager old = registerSession();
doAnswer(invocation -> {
onEdgeDisconnect(old);
return null;
}).when(old).destroyAndMarkAsZombieIfFailed();
EdgeGrpcSessionManager replacement = newSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, replacement);
verify(tsSubService, never()).saveAttributes(argThat(activeStateWrite(false)));
verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite()));
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class),
argThat(msg -> TbMsgType.DISCONNECT_EVENT.equals(msg.getInternalType())), isNull());
verify(ruleProcessor, never()).process(argThat(disconnectTrigger()));
verify(edgeIdServiceIdCache, never()).evict(edgeId);
assertThat(sessions.getByEdgeId(edgeId)).isSameAs(replacement);
assertThat(sessions.getSessionsById()).doesNotContainKey(old.getState().getSessionId());
}
@Test
void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() {
// the previous node reads this cache entry on disconnect, so the claim must be visible before active=true
EdgeGrpcSessionManager session = newSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, session);
InOrder inOrder = inOrder(edgeIdServiceIdCache, tsSubService);
inOrder.verify(edgeIdServiceIdCache).put(edgeId, THIS_NODE);
inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite(true)));
}
private void verifyNoDisconnectSideEffects() {
verify(tsSubService, never()).saveAttributes(argThat(activeStateWrite(false)));
verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite()));
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
verify(ruleProcessor, never()).process(argThat(disconnectTrigger()));
}
private void onEdgeDisconnect(EdgeGrpcSessionManager session) {
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, session.getState().getSessionId());
}
private EdgeGrpcSessionManager registerSession() {
EdgeGrpcSessionManager session = newSession();
sessions.put(session);
return session;
}
private EdgeGrpcSessionManager newSession() {
EdgeSessionState state = new EdgeSessionState();
state.setEdge(edge);
EdgeGrpcSessionManager session = mock(EdgeGrpcSessionManager.class);
lenient().when(session.getState()).thenReturn(state);
return session;
}
private ArgumentMatcher<AttributesSaveRequest> activeStateWrite(boolean active) {
return request -> request != null
&& edgeId.equals(request.getEntityId())
&& request.getEntries().stream().anyMatch(entry ->
ACTIVITY_STATE.equals(entry.getKey())
&& Boolean.valueOf(active).equals(entry.getBooleanValue().orElse(null)));
}
private ArgumentMatcher<AttributesSaveRequest> lastDisconnectTimeWrite() {
return request -> request != null
&& edgeId.equals(request.getEntityId())
&& request.getEntries().stream().anyMatch(entry -> LAST_DISCONNECT_TIME.equals(entry.getKey()));
}
private ArgumentMatcher<NotificationRuleTrigger> disconnectTrigger() {
return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger && !edgeTrigger.isConnected();
}
}

52
application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.edge.rpc.session;
import org.junit.jupiter.api.BeforeEach;
@ -11,6 +12,7 @@ import org.thingsboard.server.service.edge.rpc.EdgeSessionState;
import org.thingsboard.server.service.edge.rpc.session.manager.EdgeGrpcSessionManager;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@ -81,6 +83,54 @@ class EdgeSessionsHolderTest {
assertThat(holder.isCurrent(newSession())).isFalse();
}
@Test
void putReturnsTheSessionItReplaced() {
EdgeGrpcSessionManager first = newSession();
EdgeGrpcSessionManager second = newSession();
assertThat(holder.put(first)).isNull();
assertThat(holder.put(second)).isSameAs(first);
assertThat(holder.getByEdgeId(edgeId)).isSameAs(second);
}
@Test
void runIfNoSessionRunsTheActionWhenTheEdgeHasNoSession() {
AtomicBoolean ran = new AtomicBoolean();
assertThat(holder.runIfNoSession(edgeId, () -> ran.set(true))).isTrue();
assertThat(ran).isTrue();
}
@Test
void runIfNoSessionSkipsTheActionWhenTheEdgeHasASession() {
holder.put(newSession());
AtomicBoolean ran = new AtomicBoolean();
assertThat(holder.runIfNoSession(edgeId, () -> ran.set(true))).isFalse();
assertThat(ran).isFalse();
}
@Test
void putWaitsForARunningRunIfNoSessionAction() throws Exception {
EdgeGrpcSessionManager session = newSession();
Thread put = new Thread(() -> holder.put(session));
AtomicBoolean putBlockedDuringAction = new AtomicBoolean();
holder.runIfNoSession(edgeId, () -> {
put.start();
try {
put.join(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
putBlockedDuringAction.set(put.isAlive());
});
put.join(5000);
assertThat(putBlockedDuringAction).isTrue();
assertThat(holder.getByEdgeId(edgeId)).isSameAs(session);
}
private EdgeGrpcSessionManager newSession() {
EdgeSessionState state = new EdgeSessionState();
state.setEdge(edge);

28
common/edge-api/src/main/proto/edge.proto

@ -42,6 +42,7 @@ enum EdgeVersion {
V_4_2_2_5 = 4225;
V_4_2_2_6 = 4226;
V_4_2_2_7 = 4227;
V_4_2_2_8 = 4228;
V_4_3_0_1 = 15;
V_4_3_1 = 4310;
V_4_3_1_1 = 4311;
@ -51,7 +52,9 @@ enum EdgeVersion {
V_4_3_1_5 = 4315;
V_4_3_1_6 = 4316;
V_4_3_1_7 = 4317;
V_4_3_1_8 = 4318;
V_4_4_0 = 4400;
V_4_4_0_1 = 4401;
V_4_4_1 = 4410;
V_LATEST = 99999;
@ -384,6 +387,28 @@ message CalculatedFieldRequestMsg {
string entityType = 3;
}
// Edge-delegated send requests (mail/sms/notification). The Cloud always resolves the tenant from the
// authenticated edge session (edge.getTenantId()) and ignores tenantIdMSB/tenantIdLSB below - they are kept
// only for symmetry with other uplink messages and must not be treated as authoritative by the receiver.
// 'request' is the JSON-serialized Edge{Mail,Sms,Notification}Request payload.
message SendEmailUplinkMsg {
int64 tenantIdMSB = 1;
int64 tenantIdLSB = 2;
string request = 3;
}
message SendSmsUplinkMsg {
int64 tenantIdMSB = 1;
int64 tenantIdLSB = 2;
string request = 3;
}
message SendNotificationUplinkMsg {
int64 tenantIdMSB = 1;
int64 tenantIdLSB = 2;
string request = 3;
}
// DEPRECATED. FOR REMOVAL
message UserCredentialsRequestMsg {
option deprecated = true;
@ -584,6 +609,9 @@ message UplinkMsg {
repeated ReportTemplateUpdateMsg reportTemplateUpdateMsg = 32;
repeated SchedulerEventUpdateMsg schedulerEventUpdateMsg = 33;
repeated ApiKeyUpdateMsg apiKeyUpdateMsg = 34;
repeated SendEmailUplinkMsg sendEmailUplinkMsg = 35;
repeated SendSmsUplinkMsg sendSmsUplinkMsg = 36;
repeated SendNotificationUplinkMsg sendNotificationUplinkMsg = 37;
}
message UplinkResponseMsg {

159
msa/js-executor/api/jsExecutor.ts

@ -4,11 +4,164 @@
import vm, { Script } from 'vm';
import atob from 'atob';
import btoa from 'btoa';
import {TextDecoder} from "util";
import {TextDecoder, types} from "util";
import { _logger } from '../config/logger';
export type TbScript = Script | Function;
type SandboxErrors = {
Error: ErrorConstructor;
TypeError: TypeErrorConstructor;
RangeError: RangeErrorConstructor;
};
// The only values host helpers may return to the sandbox.
type SandboxPrimitive = string | boolean | undefined;
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
function intrinsicGetter(prototype: object, name: string): (this: unknown) => any {
return Object.getOwnPropertyDescriptor(prototype, name)!.get!;
}
const typedArrayBuffer = intrinsicGetter(typedArrayPrototype, 'buffer');
const typedArrayByteOffset = intrinsicGetter(typedArrayPrototype, 'byteOffset');
const typedArrayByteLength = intrinsicGetter(typedArrayPrototype, 'byteLength');
const dataViewBuffer = intrinsicGetter(DataView.prototype, 'buffer');
const dataViewByteOffset = intrinsicGetter(DataView.prototype, 'byteOffset');
const dataViewByteLength = intrinsicGetter(DataView.prototype, 'byteLength');
// Sandbox-realm btoa, atob and TextDecoder delegating to the host helpers of installSandboxGlobals.
// Arguments must be coerced here, with intrinsics captured before user code runs.
// invoke() rethrows sandbox-realm errors only; anything else becomes a sandbox RangeError.
const sandboxGlobalsShim = new vm.Script(`(function (h) {
'use strict';
var S = String;
var getPrototypeOf = Object.getPrototypeOf;
var errorPrototype = Error.prototype;
var SandboxRangeError = RangeError;
function isSandboxError(e) {
if (e === null || typeof e !== 'object') {
return false;
}
for (var p = getPrototypeOf(e); p !== null; p = getPrototypeOf(p)) {
if (p === errorPrototype) {
return true;
}
}
return false;
}
function invoke(fn, a, b, c, d) {
try {
return fn(a, b, c, d);
} catch (e) {
if (isSandboxError(e)) {
throw e;
}
throw new SandboxRangeError('Maximum call stack size exceeded');
}
}
globalThis.btoa = function btoa(data) { return invoke(h.btoa, S(data)); };
globalThis.atob = function atob(data) { return invoke(h.atob, S(data)); };
class TextDecoder {
constructor(label, options) { invoke(h.create, this, label === undefined ? 'utf-8' : S(label), !!(options && options.fatal), !!(options && options.ignoreBOM)); }
get encoding() { return invoke(h.prop, this, 'encoding'); }
get fatal() { return invoke(h.prop, this, 'fatal'); }
get ignoreBOM() { return invoke(h.prop, this, 'ignoreBOM'); }
decode(input, options) { return invoke(h.decode, this, input, !!(options && options.stream)); }
}
Object.defineProperty(TextDecoder.prototype, Symbol.toStringTag, {value: 'TextDecoder', configurable: true});
globalThis.TextDecoder = TextDecoder;
})`);
function toSandboxError(errors: SandboxErrors, hostError: unknown): Error {
const source = hostError instanceof Error ? hostError : new Error(String(hostError));
const errorType = source instanceof RangeError ? errors.RangeError : source instanceof TypeError ? errors.TypeError : errors.Error;
const err = new errorType(source.message);
const code = (source as NodeJS.ErrnoException).code;
if (typeof code === 'string') {
Object.defineProperty(err, 'code', {value: code, writable: true, enumerable: true, configurable: true});
}
return err;
}
function requireString(value: unknown, name: string): string {
if (typeof value !== 'string') {
throw new TypeError(`The "${name}" argument must be of type string`);
}
return value;
}
// Reads the input through host intrinsics only; the value itself is never passed on or property-accessed.
function toHostBytes(input: unknown): Uint8Array | undefined {
if (input === undefined) {
return undefined;
}
if (types.isAnyArrayBuffer(input)) {
return new Uint8Array(input);
}
if (types.isTypedArray(input)) {
return new Uint8Array(typedArrayBuffer.call(input), typedArrayByteOffset.call(input), typedArrayByteLength.call(input));
}
if (types.isDataView(input)) {
return new Uint8Array(dataViewBuffer.call(input), dataViewByteOffset.call(input), dataViewByteLength.call(input));
}
throw new TypeError('The "input" argument must be an instance of ArrayBuffer or ArrayBufferView');
}
function installSandboxGlobals(sandbox: vm.Context): void {
// Captured before user code runs, so later monkeypatching inside the sandbox has no effect.
const errors: SandboxErrors = vm.runInContext('({Error: Error, TypeError: TypeError, RangeError: RangeError})', sandbox);
const decoders = new WeakMap<object, TextDecoder>(); // host realm: user code cannot patch it
const decoderOf = (self: unknown): TextDecoder => {
const decoder = typeof self === 'object' && self !== null ? decoders.get(self) : undefined;
if (!decoder) {
throw new TypeError('Illegal invocation');
}
return decoder;
};
// The one place host results and errors cross into the sandbox.
const guard = <A extends unknown[], R extends SandboxPrimitive>(fn: (...args: A) => R) => (...args: A): R => {
let result: R;
try {
result = fn(...args);
} catch (e) {
throw toSandboxError(errors, e);
}
if ((typeof result === 'object' && result !== null) || typeof result === 'function') {
throw new errors.Error('Host value must not be returned to the sandbox');
}
return result;
};
const host = Object.assign(Object.create(null), {
btoa: guard((data: unknown) => btoa(requireString(data, 'data'))),
atob: guard((data: unknown) => atob(requireString(data, 'data'))),
create: guard((self: unknown, label: unknown, fatal: unknown, ignoreBOM: unknown) => {
if (typeof self !== 'object' || self === null || decoders.has(self)) {
throw new TypeError('Illegal invocation');
}
decoders.set(self, new TextDecoder(requireString(label, 'label'), {fatal: fatal === true, ignoreBOM: ignoreBOM === true}));
return undefined;
}),
prop: guard((self: unknown, name: unknown): SandboxPrimitive => {
const decoder = decoderOf(self);
switch (name) {
case 'encoding':
return decoder.encoding;
case 'fatal':
return decoder.fatal;
case 'ignoreBOM':
return decoder.ignoreBOM;
default:
return undefined;
}
}),
decode: guard((self: unknown, input: unknown, stream: unknown) =>
decoderOf(self).decode(toHostBytes(input), {stream: stream === true})),
});
sandboxGlobalsShim.runInContext(sandbox)(host);
}
export class JsExecutor {
useSandbox: boolean;
private logger = _logger('JsExecutor');
@ -62,9 +215,7 @@ export class JsExecutor {
ctxArgs[i] = String(args[i]);
}
sandbox.args = ctxArgs;
sandbox.btoa = btoa;
sandbox.atob = atob;
sandbox.TextDecoder = TextDecoder;
installSandboxGlobals(sandbox);
const result = script.runInContext(sandbox, {timeout: timeout});
resolve(result);
} catch (err) {

3
msa/js-executor/config/logger.ts

@ -5,8 +5,7 @@ import path from 'path';
import DailyRotateFile from 'winston-daily-rotate-file';
import { LogEntry, logLevel } from 'kafkajs';
import { createLogger, format, transports } from 'winston';
import * as Transport from 'winston-transport';
import { createLogger, format, transport as Transport, transports } from 'winston';
const { combine, timestamp, label, printf, splat } = format;

2
msa/js-executor/docker/Dockerfile

@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
#
FROM thingsboard/node:22.22.2-bookworm-slim
FROM thingsboard/node:22.23.4-bookworm-slim
ENV NODE_ENV production
ENV DOCKER_MODE true

33
msa/js-executor/package.json

@ -8,49 +8,36 @@
"scripts": {
"pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-js-executor-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-js-executor-win.exe ./target/src && node install.js",
"test": "mkdir -p target/surefire-reports && node --require ts-node/register --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=target/surefire-reports/TEST-js-executor.xml test/jsExecutor.test.ts test/oAuthBearerProvider.test.ts",
"start": "nodemon --watch '.' --ext 'ts' --exec 'ts-node server.ts'",
"start-prod": "nodemon --watch '.' --ext 'ts' --exec 'NODE_ENV=production ts-node server.ts'",
"start": "node --watch --watch-preserve-output -r ts-node/register server.ts",
"start-prod": "NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts",
"build": "tsc"
},
"dependencies": {
"@2l/kafkajs-lz4": "^1.3.2",
"atob": "^2.1.2",
"btoa": "^1.2.1",
"config": "^4.1.1",
"express": "^5.1.0",
"js-yaml": "^4.1.1",
"config": "^4.4.2",
"express": "^5.3.0",
"js-yaml": "^4.3.2",
"kafkajs": "^2.2.4",
"long": "^5.3.2",
"simple-oauth2": "^5.1.0",
"uuid-parse": "^1.1.0",
"winston": "^3.17.0",
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0"
},
"nyc": {
"exclude": [
"test",
"__tests__",
"node_modules",
"target"
]
},
"devDependencies": {
"@types/atob": "^2.1.2",
"@types/btoa": "^1.2.3",
"@types/config": "^3.3.5",
"@types/express": "~5.0.3",
"@types/node": "~22.17.2",
"@types/express": "~5.0.6",
"@types/node": "~22.20.5",
"@types/simple-oauth2": "^5.0.8",
"@types/uuid-parse": "^1.0.2",
"@yao-pkg/pkg": "^6.6.0",
"fs-extra": "^11.3.1",
"nodemon": "^3.1.10",
"@yao-pkg/pkg": "^6.24.0",
"fs-extra": "^11.4.1",
"ts-node": "^10.9.2",
"typescript": "~5.9.3"
},
"resolutions": {
"@yao-pkg/pkg/tar": ">=7.5.8"
},
"pkg": {
"assets": [
"node_modules/config/**/*.*",

2
msa/js-executor/pom.xml

@ -91,7 +91,7 @@
<goal>install-node-and-yarn</goal>
</goals>
<configuration>
<nodeVersion>v22.22.2</nodeVersion>
<nodeVersion>v22.23.4</nodeVersion>
<yarnVersion>v1.22.22</yarnVersion>
</configuration>
</execution>

29
msa/js-executor/test/coldPathProbe.ts

@ -0,0 +1,29 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { JsExecutor } from '../api/jsExecutor';
// Runs one probe as the first sandbox execution of a fresh process and reports
// whether any error caught on stack overflow came from outside the sandbox realm.
const call = process.argv[2];
(async () => {
const exec = new JsExecutor(true);
const script = await exec.compileScript(`function(msg, metadata, msgType){
var foreign;
function attempt() {
if (foreign) return;
try { ${call}; } catch (e) {
if (e === null || typeof e !== 'object' || (e.constructor !== RangeError && e.constructor !== TypeError && e.constructor !== Error)) {
foreign = String(e && e.name);
}
}
}
function recurse() { try { recurse(); } catch (e) {} attempt(); }
recurse();
return foreign ? 'foreign error: ' + foreign : 'isolated';
}`);
const out = await exec.executeScript(script, ['{}', '{}', 'X'], 20000);
process.stdout.write(String(out));
})().catch((err) => {
process.stdout.write('probe failed: ' + String(err && err.message));
});

118
msa/js-executor/test/jsExecutor.test.ts

@ -3,6 +3,9 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import path from 'node:path';
import { promisify } from 'node:util';
import { JsExecutor } from '../api/jsExecutor';
import { oauthBearerProvider } from '../queue/oAuthBearerProvider';
@ -39,6 +42,121 @@ test('sandbox passes string args through unchanged', async () => {
assert.equal(out.first, 'hello');
});
const sandboxRealmProbes: [string, string][] = [
['btoa', 'btoa.constructor'],
['atob', 'atob.constructor'],
['TextDecoder', 'TextDecoder.constructor'],
['TextDecoder instance', 'new TextDecoder().constructor.constructor'],
['TextDecoder.prototype.decode', 'TextDecoder.prototype.decode.constructor'],
['TextDecoder getter', 'Object.getOwnPropertyDescriptor(TextDecoder.prototype, "encoding").get.constructor'],
['TextDecoder constructor error', '(function(){ try { new TextDecoder("no-such-encoding"); } catch (e) { return e.constructor.constructor; } })()'],
['TextDecoder decode error', '(function(){ try { new TextDecoder().decode("not a buffer"); } catch (e) { return e.constructor.constructor; } })()'],
['TextDecoder fatal decode error', '(function(){ try { new TextDecoder("utf-8", {fatal: true}).decode(new Uint8Array([0xff])); } catch (e) { return e.constructor.constructor; } })()'],
['getter on foreign receiver', '(function(){ try { Object.getOwnPropertyDescriptor(TextDecoder.prototype, "fatal").get.call({}); } catch (e) { return e.constructor.constructor; } })()'],
['patched WeakMap/String', '(function(){ var leak; WeakMap.prototype.get = function(k){ leak = this; }; String = function(x){ return x; }; var d = new TextDecoder(); d.decode(new Uint8Array([104])); try { btoa("\\u0100"); } catch (e) {} return leak ? leak.constructor.constructor : Function; })()'],
['Error.prepareStackTrace', '(function(){ var fr; Error.prepareStackTrace = function(e, s){ fr = s; return ""; }; try { new TextDecoder("nope"); } catch (e) { e.stack; } for (var i = 0; fr && i < fr.length; i++) { var f = fr[i].getFunction && fr[i].getFunction(); if (f) return f.constructor; var t = fr[i].getThis && fr[i].getThis(); if (t && t.constructor) return t.constructor.constructor; } return Function; })()'],
// Node formats some ERR_INVALID_ARG_TYPE messages with util.inspect, which calls a custom inspect hook.
...['utf-8', 'latin1', 'utf-16le'].map((encoding): [string, string] => [`TextDecoder.decode inspect hook (${encoding})`,
`(function(){ var F; var o = Object.create(null); o[Symbol.for("nodejs.util.inspect.custom")] = function(d, opts, insp){ F = insp && insp.constructor; return "x"; };
try { new TextDecoder("${encoding}").decode(o); } catch (e) {}
var p = {}; Object.setPrototypeOf(p, ArrayBuffer.prototype); Object.defineProperty(p, "constructor", {value: ArrayBuffer}); p[Symbol.for("nodejs.util.inspect.custom")] = o[Symbol.for("nodejs.util.inspect.custom")];
try { new TextDecoder("${encoding}").decode(p); } catch (e) {}
return F || Function; })()`]),
...['btoa', 'atob'].map((fn): [string, string] => [`${fn} with patched String returning an inspectable object`,
`(function(){ var F; String = function(x){ var o = Object.create(null); o[Symbol.for("nodejs.util.inspect.custom")] = function(d, opts, insp){ F = insp && insp.constructor; return "x"; }; return o; };
try { ${fn}("a"); } catch (e) {}
return F || Function; })()`]),
];
for (const [name, functionCtor] of sandboxRealmProbes) {
test(`sandbox globals belong to the sandbox realm: ${name}`, async () => {
const exec = new JsExecutor(true);
const script = await exec.compileScript(`function(msg, metadata, msgType){
var F = ${functionCtor};
return F('return process')();
}`);
await assert.rejects(
exec.executeScript(script, ['{}', '{}', 'X'], 5000),
/process is not defined/,
'host process must not be reachable from inside the sandbox',
);
});
}
test('sandbox globals belong to the sandbox realm: resolving functions of a returned thenable', async () => {
const exec = new JsExecutor(true);
const script = await exec.compileScript(`function(msg, metadata, msgType){
return {then: function(resolve){ resolve(resolve.constructor.constructor('return process')()); }};
}`);
await assert.rejects(
exec.executeScript(script, ['{}', '{}', 'X'], 5000),
/process is not defined/,
);
});
// A stack overflow inside a helper reproduces only while its host code path is cold,
// so each probe runs as the first sandbox execution of a fresh process.
const coldPathCalls = [
"btoa('a')",
"atob('YQ==')",
"new TextDecoder('nope')",
"new TextDecoder().decode(new Uint8Array([104]))",
"new TextDecoder().encoding",
"Object.getOwnPropertyDescriptor(TextDecoder.prototype, 'fatal').get.call({})",
];
test('sandbox helpers rethrow only sandbox-realm errors on stack overflow in cold host code', async () => {
const run = promisify(execFile);
const results = await Promise.all(coldPathCalls.map(async (call) => {
const {stdout} = await run(process.execPath, ['--require', 'ts-node/register', path.join(__dirname, 'coldPathProbe.ts'), call],
{cwd: path.join(__dirname, '..'), env: {...process.env, TS_NODE_TRANSPILE_ONLY: 'true'}, timeout: 60000});
return [call, stdout];
}));
assert.deepEqual(results, coldPathCalls.map((call) => [call, 'isolated']));
});
test('sandbox btoa/atob encode, decode and coerce like the browser API', async () => {
const exec = new JsExecutor(true);
const script = await exec.compileScript(`function(msg, metadata, msgType){
return JSON.stringify([btoa('hello'), atob('aGVsbG8='), atob(btoa('\\u00ff\\u0000x')) === '\\u00ff\\u0000x', btoa(123),
btoa.name, atob.name, Object.getPrototypeOf(btoa) === Function.prototype]);
}`);
const out = await exec.executeScript(script, ['{}', '{}', 'X'], 5000);
assert.equal(out, JSON.stringify(['aGVsbG8=', 'hello', true, 'MTIz', 'btoa', 'atob', true]));
});
test('sandbox TextDecoder decodes like the host TextDecoder', async () => {
const exec = new JsExecutor(true);
const script = await exec.compileScript(`function(msg, metadata, msgType){
var bytes = new Uint8Array([0xEF, 0xBB, 0xBF, 0x68, 0xC3, 0xA9, 0xE2, 0x82, 0xAC]);
var d = new TextDecoder();
var stream = new TextDecoder();
var streamed = stream.decode(new Uint8Array([0xE2, 0x82]), {stream: true}) + stream.decode(new Uint8Array([0xAC]));
var latin = new TextDecoder('latin1');
function errorType(fn) { try { fn(); return 'none'; } catch (e) { return e instanceof RangeError ? 'RangeError' : e instanceof TypeError ? 'TypeError' : 'other'; } }
return JSON.stringify([
d.decode(bytes), d.decode(bytes.buffer), d.decode(new DataView(bytes.buffer, 3)), d.decode(),
d.decode(bytes.subarray(3)), d.decode(bytes.subarray(4, 6)), d.decode(new Uint16Array(bytes.buffer, 2, 2)),
new TextDecoder('utf-8', {ignoreBOM: true}).decode(bytes).length, streamed,
d.encoding, d.fatal, d.ignoreBOM, new TextDecoder('UTF8', {fatal: true}).fatal,
latin.encoding, latin.decode(new Uint8Array([0xE9])),
errorType(function(){ new TextDecoder('utf-8', {fatal: true}).decode(new Uint8Array([0xFF])); }),
errorType(function(){ new TextDecoder('no-such-encoding'); }),
errorType(function(){ TextDecoder.prototype.decode.call({}, bytes); }),
errorType(function(){ TextDecoder(); }),
d instanceof TextDecoder, Object.prototype.toString.call(d)]);
}`);
const out = await exec.executeScript(script, ['{}', '{}', 'X'], 5000);
assert.equal(out, JSON.stringify([
'hé€', 'hé€', 'hé€', '',
'hé€', 'é', '\uFFFDhé',
4, '€',
'utf-8', false, false, true,
'windows-1252', 'é',
'TypeError', 'RangeError', 'TypeError', 'TypeError',
true, '[object TextDecoder]']));
});
// The use_sandbox=false path is intentionally non-isolating: scripts compile
// and run in the host realm via vm.compileFunction. The two tests below codify
// that documented contract so any future behavior change shows up as a test

1465
msa/js-executor/yarn.lock

File diff suppressed because it is too large

5
msa/web-report/config/logger.ts

@ -3,11 +3,10 @@
import config from 'config';
import path from 'path';
import DailyRotateFile from 'winston-daily-rotate-file';
import { createLogger, format, transports } from 'winston';
import * as Transport from 'winston-transport';
import { createLogger, format, transport, transports } from 'winston';
const { combine, timestamp, label, printf, splat } = format;
const loggerTransports: Array<Transport> = [];
const loggerTransports: Array<transport> = [];
if (process.env.NODE_ENV !== 'production' || process.env.DOCKER_MODE === 'true') {
loggerTransports.push(new transports.Console({

2
msa/web-report/docker/Dockerfile

@ -3,7 +3,7 @@
# SPDX-License-Identifier: BUSL-1.1
#
FROM thingsboard/node:22.22.2-bookworm-slim
FROM thingsboard/node:22.23.4-bookworm-slim
ARG TARGETPLATFORM
ARG DEBIAN_FRONTEND=noninteractive

34
msa/web-report/package.json

@ -8,34 +8,24 @@
"scripts": {
"pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-web-report-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-web-report-win.exe ./target/src && node install.js",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --watch '.' --ext 'ts' --exec 'ts-node server.ts'",
"start-prod": "nodemon --watch '.' --ext 'ts' --exec 'NODE_ENV=production ts-node server.ts'",
"start": "node --watch --watch-preserve-output -r ts-node/register server.ts",
"start-prod": "NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts",
"build": "tsc"
},
"dependencies": {
"config": "~4.1.1",
"express": "~5.1.0",
"js-yaml": "^4.1.1",
"playwright-chromium": "~1.64.0",
"playwright-core": "~1.64.0",
"winston": "~3.17.0",
"config": "~4.4.2",
"express": "~5.3.0",
"js-yaml": "^4.3.2",
"playwright-chromium": "~1.64.1",
"playwright-core": "~1.64.1",
"winston": "~3.19.0",
"winston-daily-rotate-file": "~5.0.0"
},
"nyc": {
"exclude": [
"test",
"__tests__",
"node_modules",
"target"
]
},
"devDependencies": {
"@types/config": "~3.3.5",
"@types/express": "~5.0.3",
"@types/node": "~22.17.2",
"@yao-pkg/pkg": "^6.6.0",
"fs-extra": "~11.3.1",
"nodemon": "~3.1.10",
"@types/express": "~5.0.6",
"@types/node": "~22.20.5",
"@yao-pkg/pkg": "^6.24.0",
"fs-extra": "~11.4.1",
"postinstall-postinstall": "^2.1.0",
"ts-node": "~10.9.2",
"typescript": "~5.9.3"

2
msa/web-report/pom.xml

@ -86,7 +86,7 @@
<goal>install-node-and-yarn</goal>
</goals>
<configuration>
<nodeVersion>v22.22.2</nodeVersion>
<nodeVersion>v22.23.4</nodeVersion>
<yarnVersion>v1.22.22</yarnVersion>
</configuration>
</execution>

1280
msa/web-report/yarn.lock

File diff suppressed because it is too large

5
msa/web-ui/config/logger.ts

@ -3,11 +3,10 @@
import config from 'config';
import path from 'path';
import DailyRotateFile from 'winston-daily-rotate-file';
import { createLogger, format, transports } from 'winston';
import * as Transport from 'winston-transport';
import { createLogger, format, transport, transports } from 'winston';
const { combine, timestamp, label, printf, splat } = format;
const loggerTransports: Array<Transport> = [];
const loggerTransports: Array<transport> = [];
if (process.env.NODE_ENV !== 'production' || process.env.DOCKER_MODE === 'true') {
loggerTransports.push(new transports.Console({

2
msa/web-ui/docker/Dockerfile

@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
#
FROM thingsboard/node:22.22.2-bookworm-slim
FROM thingsboard/node:22.23.4-bookworm-slim
ENV NODE_ENV production
ENV DOCKER_MODE true

38
msa/web-ui/package.json

@ -8,45 +8,31 @@
"scripts": {
"pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-web-ui-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-web-ui-win.exe ./target/src && node install.js",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web ts-node server.ts'",
"start-prod": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web NODE_ENV=production ts-node server.ts'",
"start": "WEB_FOLDER=./target/web node --watch --watch-preserve-output -r ts-node/register server.ts",
"start-prod": "WEB_FOLDER=./target/web NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts",
"build": "tsc"
},
"dependencies": {
"compression": "^1.8.2",
"config": "^3.3.12",
"connect-history-api-fallback": "1.6.0",
"express": "^5.1.0",
"http": "0.0.0",
"config": "^4.4.2",
"connect-history-api-fallback": "^2.0.0",
"express": "^5.3.0",
"http-proxy": "^1.18.1",
"js-yaml": "^4.1.1",
"winston": "^3.17.0",
"js-yaml": "^4.3.2",
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0"
},
"nyc": {
"exclude": [
"test",
"__tests__",
"node_modules",
"target"
]
},
"devDependencies": {
"@types/compression": "^1.8.1",
"@types/config": "^3.3.5",
"@types/connect-history-api-fallback": "1.5.4",
"@types/express": "~5.0.3",
"@types/http-proxy": "^1.17.16",
"@types/node": "~22.17.2",
"@yao-pkg/pkg": "^6.6.0",
"fs-extra": "^11.3.1",
"nodemon": "^3.1.10",
"@types/express": "~5.0.6",
"@types/http-proxy": "^1.17.17",
"@types/node": "~22.20.5",
"@yao-pkg/pkg": "^6.24.0",
"fs-extra": "^11.4.1",
"ts-node": "^10.9.2",
"typescript": "~5.9.3"
},
"resolutions": {
"@yao-pkg/pkg/tar": ">=7.5.8"
},
"pkg": {
"assets": [
"node_modules/config/**/*.*"

2
msa/web-ui/pom.xml

@ -70,7 +70,7 @@
<goal>install-node-and-yarn</goal>
</goals>
<configuration>
<nodeVersion>v22.22.2</nodeVersion>
<nodeVersion>v22.23.4</nodeVersion>
<yarnVersion>v1.22.22</yarnVersion>
</configuration>
</execution>

4
msa/web-ui/server.ts

@ -9,7 +9,7 @@ import httpProxy from 'http-proxy';
import compression from 'compression';
import historyApiFallback from 'connect-history-api-fallback';
import { Socket } from 'net';
import { RequestHandler } from 'serve-static';
import { RequestHandler } from 'express';
const logger = _logger('main');
@ -123,7 +123,7 @@ let connections: Socket[] = [];
const staticServe = express.static(root);
const indexHtmlFallback: RequestHandler<any> = (req, res, next) => {
const indexHtmlFallback: RequestHandler = (req, res, next) => {
res.sendFile(path.join(root, 'index.html'));
};

1285
msa/web-ui/yarn.lock

File diff suppressed because it is too large

2
pom.xml

@ -75,7 +75,7 @@
<commons-lang3.version>3.18.0</commons-lang3.version> <!-- to fix CVE-2025-48924. TODO: remove when fixed in spring-boot-dependencies -->
<netty.version>4.1.138.Final</netty.version> <!-- to fix CVE-2026-44891, CVE-2026-55831, CVE-2026-55833, CVE-2026-55851, CVE-2026-56745, CVE-2026-56817, CVE-2026-56819, CVE-2026-56820, CVE-2026-56821, CVE-2026-56822, CVE-2026-59901, CVE-2026-59902, CVE-2026-59903, CVE-2026-59920, CVE-2026-62243, CVE-2026-73507, CVE-2026-75595, CVE-2026-93488, CVE-2026-93491, CVE-2026-93560, CVE-2026-100655, CVE-2026-100656, CVE-2026-100657 (supersedes earlier netty CVE pins; also retains the 4.1.134 MQTT decoder regression fix). TODO: remove when fixed in spring-boot-dependencies -->
<opentelemetry.version>1.62.0</opentelemetry.version> <!-- to fix CVE-2026-45292 (transitive opentelemetry-api). Pinned via the opentelemetry-bom import below. TODO: remove when a TB dependency pulls opentelemetry >= 1.62.0 transitively -->
<tomcat.version>10.1.60</tomcat.version> <!-- to fix CVE-2026-53434, CVE-2026-55955, CVE-2026-65182, CVE-2026-65905, CVE-2026-68525 and CVE-2026-76183. Pinned via the tomcat-embed overrides below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<tomcat.version>10.1.61</tomcat.version> <!-- to fix CVE-2026-53434, CVE-2026-55955, CVE-2026-65182, CVE-2026-65905, CVE-2026-68525, CVE-2026-76183, CVE-2026-101296 and CVE-2026-101356. Pinned via the tomcat-embed overrides below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<httpcore5.version>5.4.3</httpcore5.version> <!-- to fix CVE-2026-54399 and CVE-2026-54428 (no fix exists on the 5.3.x line; the httpclient5 5.6.4 pin below requires httpcore5 5.4.3). Pinned via the httpcore5 overrides below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<logback.version>1.5.38</logback.version> <!-- to fix CVE-2026-13006 (1.5.36 as reported by the scanner is still vulnerable; 1.5.37 removed Janino conditional processing entirely, 1.5.38 adds a HardenedObjectInputStream fix). Pinned via the logback overrides below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<jackson-bom.version>2.21.7</jackson-bom.version> <!-- to fix CVE-2026-59889, CVE-2026-68497, CVE-2026-89425 and CVE-2026-91777. Pinned via the jackson-bom import below: spring-boot-dependencies re-imports jackson-bom with its own placeholder, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->

8
tools/src/main/python/license-headers/curations.json

@ -1181,7 +1181,7 @@
"path": "msa/web-report/config/logger.ts",
"header": "busl",
"reason": "New PE module for the PE web-report service. Its body is identical to CE msa/web-ui/config/logger.ts, which PE still carries and which is a week older; the PE file is a copy for a PE-only service, not the CE file. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.",
"contentHash": "sha256:aec71ee9557d9b8f0691e46617d923403e73b03cb204c3e8c837200487337398"
"contentHash": "sha256:611c34e6267c2f0511b2a830289dbc9effd5225e89d2498c8ac7bf0cfd8b03e8"
},
{
"path": "msa/web-report/config/tb-web-report.conf",
@ -1189,6 +1189,12 @@
"reason": "Launch, logging or runtime scaffolding for a PE service. Maintainer explicitly resolved this PE module scaffolding as PE-only; matching CE startup/logging conventions do not override that decision. Reviewed similarity candidate msa/js-executor/config/tb-js-executor.conf at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 95e43f9ea9875eaed7e06ef3559914a901727636).",
"contentHash": "sha256:f4568fd8a8158238c9d60bf6fce8ea4c7a3d98959bcf1e9fb3ef91aced0a3c46"
},
{
"path": "msa/web-report/pom.xml",
"header": "busl",
"reason": "Build descriptor of the PE-only web-report module; CE has no web-report module. The only CE version is an empty file (blob e69de29bb2d) added by stray commit 2b1c5d92f3a, pushed to fix/maven-node-lts-4.3 after #16417 merged and carried into lts-4.4 via #16419; it never reached CE lts-4.3 and is not the origin of this file.",
"contentHash": "sha256:f2b9258104e62bbcff5625cad22a7a1ea7b9aad862b547e6ac1d83aafe9abaff"
},
{
"path": "report/src/main/conf/logback.xml",
"header": "busl",

3
ui-ngx/esbuild/tb-html-fallback-middleware.ts

@ -2,9 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
import type { ServerResponse } from 'node:http';
import type { Connect } from 'vite';
import type { NextHandleFunction } from 'connect';
const tbHtmlFallbackMiddleware: NextHandleFunction = (
const tbHtmlFallbackMiddleware: Connect.NextHandleFunction = (
req: Connect.IncomingMessage,
_res: ServerResponse,
next: Connect.NextFunction

97
ui-ngx/package.json

@ -13,16 +13,16 @@
},
"private": true,
"dependencies": {
"@angular/animations": "20.3.28",
"@angular/animations": "20.3.34",
"@angular/cdk": "20.2.14",
"@angular/common": "20.3.28",
"@angular/compiler": "20.3.28",
"@angular/core": "20.3.28",
"@angular/forms": "20.3.28",
"@angular/common": "20.3.34",
"@angular/compiler": "20.3.34",
"@angular/core": "20.3.34",
"@angular/forms": "20.3.34",
"@angular/material": "20.2.14",
"@angular/platform-browser": "20.3.28",
"@angular/platform-browser-dynamic": "20.3.28",
"@angular/router": "20.3.28",
"@angular/platform-browser": "20.3.34",
"@angular/platform-browser-dynamic": "20.3.34",
"@angular/router": "20.3.34",
"@auth0/angular-jwt": "^5.2.0",
"@flowjs/flow.js": "^2.14.1",
"@flowjs/ngx-flow": "20.0.2",
@ -33,19 +33,19 @@
"@fullcalendar/list": "^6.1.20",
"@fullcalendar/moment": "^6.1.20",
"@fullcalendar/timegrid": "^6.1.20",
"@geoman-io/leaflet-geoman-free": "2.19.3",
"@geoman-io/leaflet-geoman-free": "2.20.4",
"@hugerte/hugerte-angular": "~1.1.1",
"@iplab/ngx-color-picker": "^20.0.0",
"@iplab/ngx-color-picker": "^20.1.0",
"@mat-datetimepicker/core": "~16.0.1",
"@mdi/svg": "^7.4.47",
"@messageformat/core": "^3.4.0",
"@messageformat/core": "^3.4.1",
"@ngrx/effects": "^20.1.0",
"@ngrx/store": "^20.1.0",
"@ngrx/store-devtools": "^20.1.0",
"@ngx-translate/core": "^17.0.0",
"@svgdotjs/svg.filter.js": "^3.0.9",
"@svgdotjs/svg.js": "3.2.4",
"@svgdotjs/svg.panzoom.js": "^2.1.2",
"@svgdotjs/svg.filter.js": "^3.0.10",
"@svgdotjs/svg.js": "3.2.8",
"@svgdotjs/svg.panzoom.js": "^2.1.3",
"@swimlane/ngx-graph": "^11.0.0",
"ace-builds": "1.43.6",
"ace-diff": "^3.3.0",
@ -53,31 +53,31 @@
"angular-gridster2": "~20.2.4",
"angular2-hotkeys": "^16.0.1",
"canvas-gauges": "^2.1.7",
"core-js": "^3.48.0",
"dayjs": "1.11.20",
"core-js": "^3.51.0",
"dayjs": "1.11.23",
"echarts": "https://github.com/thingsboard/echarts/archive/5.5.2-TB.tar.gz",
"exceljs-hardened": "~5.0.0",
"flag-icons": "7.2.3",
"exceljs-hardened": "~5.1.0",
"flag-icons": "7.6.0",
"flot": "https://github.com/thingsboard/flot.git#0.9-work",
"flot.curvedlines": "https://github.com/MichaelZinsmaier/CurvedLines.git#master",
"font-awesome": "^4.7.0",
"html2canvas": "^1.4.1",
"hugerte": "~1.0.12",
"hugerte": "~1.0.14",
"jquery": "^3.7.1",
"jquery-sparkline": "^2.4.0",
"jquery.terminal": "^2.45.2",
"jquery.terminal": "^2.48.1",
"js-beautify": "1.15.4",
"json-schema-defaults": "^0.4.0",
"jstree": "^3.3.17",
"jstree-bootstrap-theme": "^1.0.1",
"jszip": "^3.10.1",
"jszip": "^3.10.2",
"leaflet": "1.9.4",
"leaflet-polylinedecorator": "1.6.0",
"leaflet-providers": "4.0.0",
"leaflet.gridlayer.googlemutant": "0.15.0",
"leaflet.markercluster": "1.5.3",
"libphonenumber-js": "^1.12.35",
"maplibre-gl": "6.11.2",
"libphonenumber-js": "^1.13.15",
"maplibre-gl": "6.15.0",
"marked": "~16.4.2",
"moment": "^2.31.0",
"moment-timezone": "^0.6.5",
@ -89,7 +89,7 @@
"ngx-hm-carousel": "^19.0.0",
"ngx-markdown": "^20.1.0",
"ngx-sharebuttons": "^17.0.0",
"ngx-translate-messageformat-compiler": "^7.2.0",
"ngx-translate-messageformat-compiler": "^7.3.0",
"objectpath": "^2.0.0",
"photoswipe": "^5.4.4",
"qrcode": "^1.5.4",
@ -110,52 +110,49 @@
},
"devDependencies": {
"@angular-builders/custom-esbuild": "20.0.0",
"@angular-devkit/build-angular": "20.3.34",
"@angular-devkit/core": "20.3.34",
"@angular-devkit/schematics": "20.3.34",
"@angular/build": "20.3.34",
"@angular/cli": "20.3.34",
"@angular/compiler-cli": "20.3.28",
"@angular/language-service": "20.3.28",
"@angular-devkit/core": "20.3.41",
"@angular-devkit/schematics": "20.3.41",
"@angular/build": "20.3.41",
"@angular/cli": "20.3.41",
"@angular/compiler-cli": "20.3.34",
"@angular/language-service": "20.3.34",
"@types/ace-diff": "^2.1.4",
"@types/canvas-gauges": "^2.1.8",
"@types/flot": "^0.0.36",
"@types/flowjs": "^2.13.14",
"@types/jquery": "^3.5.33",
"@types/jquery": "^3.5.34",
"@types/js-beautify": "^1.14.3",
"@types/leaflet": "1.9.14",
"@types/leaflet-polylinedecorator": "1.6.4",
"@types/leaflet-providers": "1.2.4",
"@types/leaflet.gridlayer.googlemutant": "0.4.9",
"@types/leaflet.markercluster": "1.5.5",
"@types/lodash": "^4.17.22",
"@types/node": "~22.18.13",
"@types/raphael": "^2.3.9",
"@types/systemjs": "6.15.3",
"@types/leaflet": "1.9.22",
"@types/leaflet-polylinedecorator": "1.6.5",
"@types/leaflet-providers": "1.2.5",
"@types/leaflet.gridlayer.googlemutant": "0.4.11",
"@types/leaflet.markercluster": "1.5.6",
"@types/lodash": "^4.17.27",
"@types/node": "~22.20.5",
"@types/raphael": "^2.3.10",
"@types/systemjs": "6.15.4",
"@types/tinycolor2": "^1.4.6",
"@types/tooltipster": "^0.0.35",
"angular-eslint": "~20.7.0",
"autoprefixer": "^10.4.23",
"directory-tree": "^3.5.2",
"eslint": "9.39.4",
"autoprefixer": "^10.6.1",
"directory-tree": "^3.6.0",
"eslint": "9.39.5",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jsdoc": "^62.4.1",
"eslint-plugin-jsdoc": "^62.9.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-tailwindcss": "^3.18.2",
"eslint-plugin-tailwindcss": "^3.18.3",
"ngrx-store-freeze": "^0.2.4",
"patch-package": "^8.0.1",
"postcss": "^8.5.6",
"postcss": "^8.5.31",
"postinstall-prepare": "^2.0.0",
"tailwindcss": "^3.4.19",
"ts-node": "^10.9.2",
"typescript": "~5.9.3",
"typescript-eslint": "^8.54.0"
"typescript-eslint": "^8.72.0"
},
"resolutions": {
"@babel/core": "7.29.7",
"esbuild": "0.28.1",
"rollup": "4.59.0",
"less": ">=4.9.0",
"js-beautify/**/minimatch": "^9.0.7"
}
}

0
ui-ngx/patches/@angular+build+20.3.34.patch → ui-ngx/patches/@angular+build+20.3.41.patch

0
ui-ngx/patches/@angular+core+20.3.28.patch → ui-ngx/patches/@angular+core+20.3.34.patch

0
ui-ngx/patches/@iplab+ngx-color-picker+20.0.0.patch → ui-ngx/patches/@iplab+ngx-color-picker+20.1.0.patch

2
ui-ngx/pom.xml

@ -57,7 +57,7 @@
<goal>install-node-and-yarn</goal>
</goals>
<configuration>
<nodeVersion>v22.22.2</nodeVersion>
<nodeVersion>v22.23.4</nodeVersion>
<yarnVersion>v1.22.22</yarnVersion>
</configuration>
</execution>

14
ui-ngx/src/app/core/http/ai-chat.service.ts

@ -54,9 +54,21 @@ export class AiChatService {
}
public sendChatMessage(chatId: string, request: SendChatMessageRequest, config?: RequestConfig): Observable<ChatEvent> {
return this.streamEvents(`/api/ai/chats/${chatId}/messages`, request, config);
}
/**
* Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the
* live ones. Completes with no events when nothing is running.
*/
public resumeChat(chatId: string, config?: RequestConfig): Observable<ChatEvent> {
return this.streamEvents(`/api/ai/chats/${chatId}/resume`, null, config);
}
private streamEvents(url: string, body: any, config?: RequestConfig): Observable<ChatEvent> {
let lastLength = 0;
let buffer = '';
return this.http.post(`/api/ai/chats/${chatId}/messages`, request, {
return this.http.post(url, body, {
...defaultHttpOptions(config?.ignoreLoading, config?.ignoreErrors),
observe: 'events',
reportProgress: true,

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

@ -10,11 +10,13 @@ import {
OnInit,
SecurityContext,
signal,
untracked,
ViewChild
} from '@angular/core';
import { ChatMessage } from '@shared/models/solution-creator.models';
import { Observable, of, Subject } from 'rxjs';
import { concatMap, finalize, switchMap, takeUntil, tap } from 'rxjs/operators';
import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models';
import { Observable, of, Subject, throwError, timer } from 'rxjs';
import { concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { AiChatService } from '@core/http/ai-chat.service';
import {
AiAssistantPromptExample,
@ -145,11 +147,20 @@ export class AiAssistantPanelComponent implements OnInit {
private cancelMessage$ = new Subject<void>();
private sessionAffectedEntities: EntityId[] = [];
private messageCancelled = false;
private resumeOnOpen = false;
private static readonly RESUME_ATTEMPTS = 4;
private static readonly RESUME_DELAY_MS = 2000;
private openEffect = effect(() => {
if (this.panelService.open()) {
this.dropChatFromOtherContext();
this.loadChats();
const chatId = untracked(() => this.chatId());
if (this.resumeOnOpen && chatId) {
this.resumeOnOpen = false;
this.loadChat$.next(chatId);
}
} else {
this.slideDone.set(false);
this.suspendOnClose();
@ -177,7 +188,8 @@ export class AiAssistantPanelComponent implements OnInit {
}),
takeUntilDestroyed(this.destroyRef)
).subscribe(messages => {
this.messages.set(messages);
this.showHistory(messages);
this.resumeTurn(this.chatId());
});
}
@ -224,10 +236,16 @@ export class AiAssistantPanelComponent implements OnInit {
}
sendMsgFromUser(msg: string): void {
this.messages.update(list => [...list, {from: 'USER', content: msg}]);
const userMessage: ChatMessage = {from: 'USER', content: msg};
this.messages.update(list => [...list, userMessage]);
this.sendMessage(msg).subscribe({
error: (err) => {
this.messages.update(list => list.slice(0, -1));
if (this.isConnectionLost(err) && this.chatId()) {
this.showErrorToast(this.translate.instant('ai-assistant.connection-lost'));
this.resumeTurn(this.chatId(), true);
return;
}
this.messages.update(list => list.filter(message => message !== userMessage));
setTimeout(() => {
this.showErrorMessage(err);
}, 0);
@ -254,13 +272,11 @@ export class AiAssistantPanelComponent implements OnInit {
this.promptInput?.reset();
}
// Keeps the open chat so reopening shows it right away, unless an interrupted reply left it stale.
// Keeps the open chat so reopening shows it right away. A reply interrupted by closing keeps running on the
// server, so reopening reloads the chat and follows that reply.
private suspendOnClose(): void {
if (this.loading()) {
this.reset();
} else {
this.cancelActiveMessage();
}
this.resumeOnOpen = this.loading();
this.cancelActiveMessage();
}
private dropChatFromOtherContext(): void {
@ -379,6 +395,90 @@ export class AiAssistantPanelComponent implements OnInit {
return (!chatId || !isEqual(currentContext, alreadySent)) ? currentContext : undefined;
}
private showHistory(messages: ChatMessage[]): void {
const completed: Record<string, ToolExecutionResult> = {};
for (const message of messages) {
if (message.from === 'APPROVAL' && (message as ApprovalChatMessage).result) {
const result = (message as ApprovalChatMessage).result;
completed[result.executionId] = result;
}
}
this.completedExecutions.set(completed);
this.messages.set(messages);
}
// Follows the reply still running in the chat, if any: after a reload, a reopened panel or a lost connection.
// The server replays the whole reply, so what the history already shows of it is dropped first.
private resumeTurn(chatId: string, afterConnectionLoss = false): void {
if (!chatId) {
return;
}
let resumed = false;
this.messageCancelled = false;
this.sessionAffectedEntities = [];
const attempt$ = timer(afterConnectionLoss ? AiAssistantPanelComponent.RESUME_DELAY_MS : 0).pipe(
tap(() => {
if (afterConnectionLoss) {
this.initLoadingState();
}
}),
switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true}))
);
attempt$.pipe(
retry({
count: afterConnectionLoss ? AiAssistantPanelComponent.RESUME_ATTEMPTS : 0,
delay: (error, attempt) => this.isConnectionLost(error)
? timer(attempt * AiAssistantPanelComponent.RESUME_DELAY_MS)
: throwError(() => error)
}),
takeUntil(this.cancelMessage$),
concatMap(event => {
if (event.event === 'turnResumed') {
resumed = true;
this.initLoadingState();
this.dropRunningReply();
return of(event);
}
return this.handleChatEvent(event);
}),
finalize(() => {
if (resumed || afterConnectionLoss) {
this.stopLoadingState();
}
})
).subscribe({
error: () => {
if (afterConnectionLoss) {
this.showErrorToast(this.translate.instant('ai-assistant.reconnect-failed'));
}
},
complete: () => {
if (this.messageCancelled || this.chatId() !== chatId) {
return;
}
if (this.sessionAffectedEntities.length) {
this.panelService.emitUpdatedData(this.sessionAffectedEntities);
}
if (resumed || afterConnectionLoss) {
this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true})
.pipe(takeUntil(this.cancelMessage$))
.subscribe(messages => this.showHistory(messages));
}
}
});
}
private dropRunningReply(): void {
this.messages.update(list => {
const lastUser = list.map(message => message.from).lastIndexOf('USER');
return lastUser >= 0 ? list.slice(0, lastUser + 1) : list;
});
}
private isConnectionLost(error: any): boolean {
return error instanceof HttpErrorResponse && error.status === 0;
}
private handleChatEvent(chatMsg: ChatEvent): Observable<ChatEvent> {
switch (chatMsg.event) {
case 'assistantMessage':

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

@ -18,6 +18,11 @@
[autoApprove]="autoApprove"
(approvalAction)="approval($event)">
</tb-ai-approval-card>
} @else if (msg.status === 'INCOMPLETE') {
<div class="incomplete flex items-start gap-2">
<mat-icon class="incomplete-icon">warning_amber</mat-icon>
<span>{{ msg.content }}</span>
</div>
} @else {
<tb-markdown usePlainMarkdown [additionalStyles]="additionalStyles" [data]="parseResult(msg.content)"></tb-markdown>
}

16
ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss

@ -41,6 +41,22 @@
}
}
.incomplete {
padding: 10px 14px;
border-radius: 12px;
line-height: 20px;
color: rgba(0, 0, 0, 0.76);
background: rgba(255, 152, 0, 0.08);
.incomplete-icon {
flex: none;
color: #FF9800;
font-size: 20px;
width: 20px;
height: 20px;
}
}
.generating {
transition: all 0.3s ease-in-out;

69
ui-ngx/src/app/modules/home/components/widget/lib/action/action-widget.models.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
AttributeData,
AttributeScope,
@ -10,6 +11,7 @@ import {
import { WidgetContext } from '@home/models/widget-component.models';
import {
BehaviorSubject,
defer,
forkJoin,
merge,
Observable,
@ -27,7 +29,10 @@ import {
DataToValueType,
GetAttributeValueSettings,
GetValueAction,
GetValueRpcSettings,
GetValueSettings,
RpcParamsSettings,
RpcParamsType,
RpcSettings,
SetAttributeValueSettings,
SetValueAction,
@ -40,7 +45,7 @@ import {
import { ValueType } from '@shared/models/constants';
import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models';
import { EntityId } from '@shared/models/id/entity-id';
import { deepClone, isDefinedAndNotNull } from '@core/utils';
import { deepClone, isDefined, isDefinedAndNotNull } from '@core/utils';
import { parseError } from '@shared/models/error.models';
import { CompiledTbFunction, compileTbFunction } from '@shared/models/js-function.models';
import { HttpClient } from '@angular/common/http';
@ -426,9 +431,51 @@ export class DefaultValueGetter<V> extends ValueGetter<V> {
}
}
type RpcParamsFunction = () => any;
export class RpcParamsConverter {
private readonly paramsFunction$: Observable<CompiledTbFunction<RpcParamsFunction>>;
constructor(private http: HttpClient,
private settings: RpcParamsSettings) {
if (settings?.type === RpcParamsType.FUNCTION) {
this.paramsFunction$ = defer(() => compileTbFunction<RpcParamsFunction>(this.http, settings.paramsFunction)).pipe(
catchError(() => {
return of(new CompiledTbFunction(() => null, []));
}),
share({
connector: () => new ReplaySubject(1),
resetOnError: false,
resetOnComplete: false,
resetOnRefCountZero: false
})
);
}
}
params(): Observable<any> {
switch (this.settings?.type) {
case RpcParamsType.CONSTANT:
return of(isDefined(this.settings.constantValue) ? this.settings.constantValue : null);
case RpcParamsType.FUNCTION:
return this.paramsFunction$.pipe(
map((paramsFunction) => {
const params = paramsFunction.execute();
return isDefined(params) ? params : null;
}),
catchError(() => of(null))
);
default:
return of(null);
}
}
}
export class ExecuteRpcValueGetter<V> extends ValueGetter<V> {
private readonly executeRpcSettings: RpcSettings;
private readonly executeRpcSettings: GetValueRpcSettings;
private readonly rpcParamsConverter: RpcParamsConverter;
constructor(protected ctx: WidgetContext,
protected settings: GetValueSettings<V>,
@ -437,6 +484,7 @@ export class ExecuteRpcValueGetter<V> extends ValueGetter<V> {
protected simulated: boolean) {
super(ctx, settings, valueType, valueObserver, simulated);
this.executeRpcSettings = settings.executeRpc;
this.rpcParamsConverter = new RpcParamsConverter(ctx.http, this.executeRpcSettings.params);
}
protected doGetValue(): Observable<V> {
@ -444,12 +492,19 @@ export class ExecuteRpcValueGetter<V> extends ValueGetter<V> {
const defaultValue = isDefinedAndNotNull(this.settings.defaultValue) ? this.settings.defaultValue : null;
return of(defaultValue).pipe(delay(500));
} else {
return this.ctx.controlApi.sendTwoWayCommand(this.executeRpcSettings.method, null,
this.executeRpcSettings.requestTimeout,
this.executeRpcSettings.requestPersistent,
this.executeRpcSettings.persistentPollingInterval).pipe(
return this.rpcParamsConverter.params().pipe(
switchMap(params => this.ctx.controlApi.sendTwoWayCommand(this.executeRpcSettings.method, params,
this.executeRpcSettings.requestTimeout,
this.executeRpcSettings.requestPersistent,
this.executeRpcSettings.persistentPollingInterval)),
catchError((err) => {
throw handleRpcError(this.ctx, err);
}),
share({
connector: () => new ReplaySubject(1),
resetOnError: false,
resetOnComplete: false,
resetOnRefCountZero: true
})
);
}

4
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-resources-tabs.component.html

@ -1,7 +1,8 @@
<!--
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
-->
<mat-tab-group selectedIndex="{{hasCustomFunction ? 3 : 2}}" dynamicHeight="true" style="width: 100%; height: 100%;">
@ -12,6 +13,7 @@
<div class="flex flex-1 flex-row items-center justify-start"
style="padding-top: 10px;">
<tb-resource-autocomplete class="mat-block flex-1"
appearance="outline"
subscriptSizing="dynamic"
hideRequiredMarker required
[allowAutocomplete]="resource.isModule"

36
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/get-value-action-settings-panel.component.html

@ -1,7 +1,8 @@
<!--
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
-->
<div class="tb-action-settings-panel" [formGroup]="getValueSettingsFormGroup">
@ -46,6 +47,39 @@
}
</mat-form-field>
</div>
<ng-container formGroupName="executeRpc">
<div class="tb-form-panel stroked" formGroupName="params">
<div class="tb-form-row no-padding no-border column-xs">
<div class="fixed-title-width" translate>widgets.value-action.parameters</div>
<tb-toggle-select class="flex-1" formControlName="type">
<tb-toggle-option [value]="rpcParamsType.CONSTANT">{{ 'widgets.value-action.converter-constant' | translate }}</tb-toggle-option>
<tb-toggle-option [value]="rpcParamsType.FUNCTION">{{ 'widgets.value-action.converter-function' | translate }}</tb-toggle-option>
<tb-toggle-option [value]="rpcParamsType.NONE">{{ 'widgets.value-action.converter-none' | translate }}</tb-toggle-option>
</tb-toggle-select>
</div>
@if (getValueSettingsFormGroup.get('executeRpc').get('params').get('type').value === rpcParamsType.CONSTANT) {
<tb-value-input
class="flex-1"
[layout]="{
layout: 'row',
breakpoints: {xs: 'column'}
}"
formControlName="constantValue">
</tb-value-input>
}
@if (getValueSettingsFormGroup.get('executeRpc').get('params').get('type').value === rpcParamsType.FUNCTION) {
<tb-js-func
formControlName="paramsFunction"
withModules
required
[globalVariables]="functionScopeVariables"
[functionArgs]="[]"
functionTitle="{{ 'widgets.value-action.rpc-params-function' | translate }}"
helpId="widget/lib/rpc/rpc_params_fn">
</tb-js-func>
}
</div>
</ng-container>
}
@case (getValueAction.GET_ATTRIBUTE) {
<ng-container formGroupName="getAttribute">

29
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/get-value-action-settings-panel.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, DestroyRef, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { PageComponent } from '@shared/components/page.component';
import { TbPopoverComponent } from '@shared/components/popover.component';
@ -12,7 +13,8 @@ import {
GetValueAction,
getValueActionsByWidgetType,
getValueActionTranslations,
GetValueSettings
GetValueSettings,
RpcParamsType
} from '@shared/models/action-widget-settings.models';
import { ValueType } from '@shared/models/constants';
import { TargetDevice, widgetType } from '@shared/models/widget.models';
@ -80,6 +82,8 @@ export class GetValueActionSettingsPanelComponent extends PageComponent implemen
dataToValueType = DataToValueType;
rpcParamsType = RpcParamsType;
functionScopeVariables = this.widgetService.getWidgetScopeVariables();
ValueType = ValueType;
@ -109,7 +113,12 @@ export class GetValueActionSettingsPanelComponent extends PageComponent implemen
requestTimeout: [this.getValueSettings?.executeRpc?.requestTimeout, [Validators.required, Validators.min(5000)]],
requestPersistent: [this.getValueSettings?.executeRpc?.requestPersistent, []],
persistentPollingInterval:
[this.getValueSettings?.executeRpc?.persistentPollingInterval, [Validators.required, Validators.min(1000)]]
[this.getValueSettings?.executeRpc?.persistentPollingInterval, [Validators.required, Validators.min(1000)]],
params: this.fb.group({
type: [this.getValueSettings?.executeRpc?.params?.type ?? RpcParamsType.NONE, [Validators.required]],
constantValue: [this.getValueSettings?.executeRpc?.params?.constantValue, [Validators.required]],
paramsFunction: [this.getValueSettings?.executeRpc?.params?.paramsFunction, [Validators.required]]
})
}),
getAttribute: this.fb.group({
scope: [this.getValueSettings?.getAttribute?.scope, []],
@ -136,7 +145,8 @@ export class GetValueActionSettingsPanelComponent extends PageComponent implemen
merge(this.getValueSettingsFormGroup.get('action').valueChanges,
this.getValueSettingsFormGroup.get('dataToValue').get('type').valueChanges,
this.getValueSettingsFormGroup.get('executeRpc').get('requestPersistent').valueChanges
this.getValueSettingsFormGroup.get('executeRpc').get('requestPersistent').valueChanges,
this.getValueSettingsFormGroup.get('executeRpc').get('params').get('type').valueChanges
).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe(() => {
@ -185,6 +195,17 @@ export class GetValueActionSettingsPanelComponent extends PageComponent implemen
} else {
this.getValueSettingsFormGroup.get('executeRpc').get('persistentPollingInterval').disable({emitEvent: false});
}
const paramsType: RpcParamsType = this.getValueSettingsFormGroup.get('executeRpc').get('params').get('type').value;
if (paramsType === RpcParamsType.CONSTANT) {
this.getValueSettingsFormGroup.get('executeRpc').get('params').get('constantValue').enable({emitEvent: false});
} else {
this.getValueSettingsFormGroup.get('executeRpc').get('params').get('constantValue').disable({emitEvent: false});
}
if (paramsType === RpcParamsType.FUNCTION) {
this.getValueSettingsFormGroup.get('executeRpc').get('params').get('paramsFunction').enable({emitEvent: false});
} else {
this.getValueSettingsFormGroup.get('executeRpc').get('params').get('paramsFunction').disable({emitEvent: false});
}
break;
case GetValueAction.GET_ATTRIBUTE:
this.getValueSettingsFormGroup.get('getAttribute').enable({emitEvent: false});

1
ui-ngx/src/app/modules/home/components/widget/widget.component.ts

@ -1561,6 +1561,7 @@ export class WidgetComponent extends PageComponent implements OnInit, OnChanges,
embedded: true,
syncStateWithQueryParam: false,
hideToolbar: hideDashboardToolbar,
hideMainToolbar: false,
currentState: objToBase64([stateObject]),
dashboard,
parentDashboard: this.widgetContext.parentDashboard ?

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

@ -67,7 +67,7 @@
<mat-icon>menu</mat-icon>
</button>
<button mat-icon-button
[class.!hidden]="!forceFullscreen || displaySearchMode"
[class.!hidden]="!forceFullscreen || displaySearchMode()"
(click)="goBack()">
<mat-icon>arrow_back</mat-icon>
</button>

2
ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.html

@ -15,7 +15,7 @@
(click)="goBack()">
<mat-icon>arrow_back</mat-icon>
</button>
<span class="mat-headline-5">{{ widgetsBundle.title }}: {{ 'widget.widgets' | translate }}</span>
<span class="mat-headline-5" tbTruncateWithTooltip>{{ widgetsBundle.title }}: {{ 'widget.widgets' | translate }}</span>
<span class="flex-1"></span>
@if (!isReadOnly) {
<button mat-flat-button color="primary" [disabled]="isLoading$ | async"

5
ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.scss

@ -13,6 +13,7 @@
.tb-bundle-widgets-card {
.mat-mdc-card-header-text {
flex: 1;
min-width: 0;
}
}
}
@ -39,6 +40,10 @@
gap: 8px;
.mat-headline-5 {
margin: 0;
min-width: 0;
}
> button {
flex-shrink: 0;
}
}

2146
ui-ngx/src/app/shared/models/ace/tbel/worker-tbel.js

File diff suppressed because it is too large

21
ui-ngx/src/app/shared/models/action-widget-settings.models.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { AttributeScope } from '@shared/models/telemetry/telemetry.models';
import { widgetType } from '@shared/models/widget.models';
import { AlarmSeverity } from '@shared/models/alarm.models';
@ -44,6 +45,22 @@ export interface RpcSettings {
persistentPollingInterval: number;
}
export enum RpcParamsType {
NONE = 'NONE',
CONSTANT = 'CONSTANT',
FUNCTION = 'FUNCTION'
}
export interface RpcParamsSettings {
type: RpcParamsType;
constantValue?: any;
paramsFunction?: TbFunction;
}
export interface GetValueRpcSettings extends RpcSettings {
params?: RpcParamsSettings;
}
export interface AlarmStatusSettings {
severityList: Array<AlarmSeverity>;
typeList: Array<string>;
@ -79,7 +96,7 @@ export interface ValueActionSettings {
export interface GetValueSettings<V> extends ValueActionSettings {
action: GetValueAction;
defaultValue: V;
executeRpc?: RpcSettings;
executeRpc?: GetValueRpcSettings;
getAttribute: GetAttributeValueSettings;
getTimeSeries: TelemetryValueSettings;
getAlarmStatus: AlarmStatusSettings;

8
ui-ngx/src/app/shared/models/ai-chat.models.ts

@ -85,6 +85,11 @@ export interface ChatTitleGeneratedEvent extends BaseChatEvent {
};
}
export interface TurnResumedEvent extends BaseChatEvent {
event: 'turnResumed';
data: Record<string, never>;
}
export interface ApprovalResult {
executionId: string;
approved: boolean;
@ -97,7 +102,8 @@ export enum ToolApprovalResult {
TIMEOUT = 'TIMEOUT'
}
export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent;
export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent
| TurnResumedEvent;
export enum AiAssistantViewType {
DASHBOARD = 'DASHBOARD',

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

@ -7,7 +7,7 @@ import { EntityId } from '@shared/models/id/entity-id';
import { BaseData } from '@shared/models/base-data';
import { CalculatedFieldType } from '@shared/models/calculated-field.models';
import { AlarmSeverity } from '@shared/models/alarm.models';
import { ToolExecutionRequested } from '@shared/models/ai-chat.models';
import { ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models';
export interface SolutionInfo {
id: string;
@ -177,11 +177,13 @@ export type ChatMessage = GeneralChatMessage | ApprovalChatMessage;
export interface GeneralChatMessage {
from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE';
content: string;
status?: 'INCOMPLETE';
}
export interface ApprovalChatMessage {
from: 'APPROVAL';
data: ToolExecutionRequested;
result?: ToolExecutionResult;
}
export enum AiMetricType {

33
ui-ngx/src/assets/help/en_US/widget/lib/rpc/rpc_params_fn.md

@ -0,0 +1,33 @@
#### RPC parameters function
<div class="divider"></div>
<br/>
*function (): any*
A JavaScript function returning the parameters (payload) of the RPC command used to get the value.
**Returns:**
Payload object or primitive to be used as the parameters of the RPC get value command.
<div class="divider"></div>
##### Examples
* Request the state of a specific pin:
```javascript
return { pin: 5 };
{:copy-code}
```
* Request several values with a single RPC call:
```javascript
return { keys: ['temperature', 'humidity'] };
{:copy-code}
```
<br>
<br>

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

@ -712,6 +712,8 @@
"denied": "Denied",
"error": "Failed",
"thinking": "Thinking...",
"connection-lost": "Connection to the AI Assistant was lost. Reconnecting...",
"reconnect-failed": "Couldn't reconnect to the AI Assistant. Reopen the chat to see its reply.",
"rename-chat-title": "Rename this chat",
"export-chat": "Export chat",
"main-title": "Hello! I'm your AI Assistant"
@ -13735,6 +13737,7 @@
"state-when-result-is": "'{{state}}' when result is",
"parameters": "Parameters",
"convert-value-function": "Convert value function",
"rpc-params-function": "RPC parameters function",
"error": {
"target-entity-is-not-set": "Target entity is not set!",
"failed-to-perform-action": "Failed to perform the <b>{{ actionLabel }}</b> action.",

12
ui-ngx/src/scss/flags.scss

@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
@import 'flag-icons/sass/_variables';
$flag-icons-path: '/assets/flags';
$flag-icons-rect-path: '';
$flag-icons-use-square: false;
@import 'flag-icons/sass/_flag-icons-base';
@import 'flag-icons/sass/_flag-icons-list';
@use 'flag-icons/sass/variables' with (
$flag-icons-path: '/assets/flags',
$flag-icons-rect-path: '',
$flag-icons-use-square: false
);
@use 'flag-icons/sass/flag-icons-list';

4994
ui-ngx/yarn.lock

File diff suppressed because it is too large
Loading…
Cancel
Save