Browse Source

Merge pull request #16438 from thingsboard/rc

Merge rc into master
pull/16446/head
Vladyslav Prykhodko 1 month ago
committed by GitHub
parent
commit
7a53801216
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 26
      CONTRIBUTING.md
  2. 14
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  3. 11
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  4. 13
      application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java
  5. 2
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  6. 20
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  7. 48
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  8. 12
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  9. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java
  10. 41
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnLink.java
  11. 13
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/BaseUserProcessor.java
  12. 7
      application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java
  13. 12
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerOnPremiseTest.java
  14. 42
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerTest.java
  15. 10
      application/src/test/java/org/thingsboard/server/controller/TranslationControllerTest.java
  16. 74
      application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
  17. 51
      application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
  18. 48
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  19. 95
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
  20. 10
      application/src/test/java/org/thingsboard/server/service/ai/transport/FakeTbAiServer.java
  21. 6
      tools/src/main/python/license-headers/curations.json
  22. 14
      ui-ngx/src/app/core/http/ai-chat.service.ts
  23. 124
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  24. 5
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  25. 16
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  26. 8
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  27. 4
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  28. 2
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  29. 12
      ui-ngx/src/scss/flags.scss

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

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

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;

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)

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

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

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

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

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

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;

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 {

2
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"

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

Loading…
Cancel
Save