Browse Source

Merge pull request #16571 from thingsboard/rc

Merge rc into master
pull/16279/merge
Vladyslav Prykhodko 4 weeks ago
committed by GitHub
parent
commit
cd25989292
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 88
      application/src/main/java/org/thingsboard/server/controller/AiResourceController.java
  2. 15
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  3. 12
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  4. 24
      application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java
  5. 84
      application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java
  6. 3
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  7. 14
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  8. 4
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
  9. 4
      application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java
  10. 224
      application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java
  11. 17
      application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
  12. 17
      application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
  13. 1
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
  14. 2
      pom.xml
  15. 218
      ui-ngx/src/app/core/http/ai-resource.service.ts
  16. 6
      ui-ngx/src/app/core/http/solutions-creator.service.ts
  17. 39
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html
  18. 7
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss
  19. 33
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  20. 32
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html
  21. 50
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss
  22. 74
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts
  23. 189
      ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts
  24. 30
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html
  25. 101
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss
  26. 70
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts
  27. 8
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  28. 17
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  29. 1
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  30. 132
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html
  31. 452
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss
  32. 396
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts
  33. 118
      ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts
  34. 11
      ui-ngx/src/app/modules/home/components/ai/ai.module.ts
  35. 59
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts
  36. 6
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html
  37. 17
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts
  38. 25
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  39. 3
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  40. 6639
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  41. 26
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  42. 10094
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  43. 6233
      ui-ngx/src/assets/locale/locale.constant-no_NO.json
  44. 5589
      ui-ngx/src/assets/locale/locale.constant-sl_SI.json
  45. 111
      ui-ngx/src/styles.scss

88
application/src/main/java/org/thingsboard/server/controller/AiResourceController.java

@ -0,0 +1,88 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.resource.AiResourceService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.UUID;
@RequiredArgsConstructor
@RestController
@TbCoreComponent
@RequestMapping("/api/ai/resources")
class AiResourceController extends BaseController {
private final AiResourceService aiResourceService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/config")
public JsonNode getConfig() throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
return aiResourceService.getConfig(user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public JsonNode uploadResource(@RequestPart("file") MultipartFile file) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiResourceService.upload(file, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/{resourceId}")
public ResponseEntity<byte[]> downloadResource(@PathVariable UUID resourceId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(content.mediaType()))
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name()))
.header("X-Content-Type-Options", "nosniff")
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate())
.body(content.data());
}
private static String disposition(String name) {
ContentDisposition.Builder builder = ContentDisposition.attachment();
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name);
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString();
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@DeleteMapping("/{resourceId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteResource(@PathVariable UUID resourceId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
aiResourceService.delete(resourceId, user);
}
}

15
application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java

@ -5,6 +5,7 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -24,6 +25,7 @@ import org.thingsboard.server.service.ai.solution.AiSolutionService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.List;
import java.util.UUID;
import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER;
@ -61,16 +63,27 @@ public class AiSolutionController extends BaseController {
return aiSolutionService.getSolutions(user);
}
@Deprecated(forRemoval = true)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/{step}/chat")
public JsonNode chat(@PathVariable UUID solutionId,
@PathVariable SolutionStep step,
@RequestBody String message) throws ThingsboardException {
return sendMessage(solutionId, step, new SolutionChatMessage(message, null));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(value = "/{solutionId}/{step}/messages", consumes = MediaType.APPLICATION_JSON_VALUE)
public JsonNode sendMessage(@PathVariable UUID solutionId,
@PathVariable SolutionStep step,
@RequestBody SolutionChatMessage request) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.chat(solutionId, step, message, user);
return aiSolutionService.chat(solutionId, step, request.message(), request.resources(), user);
}
record SolutionChatMessage(String message, List<UUID> resources) {}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/create")
public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException {

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

@ -166,10 +166,20 @@ class DefaultTbAiService implements TbAiService {
if (response.isSuccess()) {
return response.getValue();
} else {
throw new ThingsboardRuntimeException(response.getError(), ThingsboardErrorCode.GENERAL);
throw new ThingsboardRuntimeException(response.getError(), toErrorCode(response.getStatus()));
}
}
static ThingsboardErrorCode toErrorCode(int status) {
return switch (status) {
case 400, 413, 415, 422 -> ThingsboardErrorCode.BAD_REQUEST_PARAMS;
case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND;
case 409 -> ThingsboardErrorCode.VERSION_CONFLICT;
case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS;
default -> ThingsboardErrorCode.GENERAL;
};
}
private void checkApiUsage(SecurityUser user) {
if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) {
throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS);

24
application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java

@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.resource;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
public interface AiResourceService {
JsonNode getConfig(SecurityUser user);
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException;
AiResourceContent download(UUID resourceId, SecurityUser user);
void delete(UUID resourceId, SecurityUser user);
record AiResourceContent(String name, String mediaType, byte[] data) {}
}

84
application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java

@ -0,0 +1,84 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.resource;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ResourceOperationRequest;
import org.thingsboard.ai.common.channel.ResourceUploadRequest;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
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.security.model.SecurityUser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
@Service
@TbCoreComponent
@RequiredArgsConstructor
class DefaultAiResourceService implements AiResourceService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override
public JsonNode getConfig(SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false);
}
@Override
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException {
if (file == null || file.isEmpty()) {
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
long maxSize = getConfig(user).path("maxSize").asLong(0);
if (maxSize > 0 && file.getSize() > maxSize) {
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
String data;
try {
data = base64(file);
} catch (IOException e) {
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL);
}
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false);
}
private static String base64(MultipartFile file) throws IOException {
var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4));
try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) {
in.transferTo(encoder);
}
return encoded.toString(StandardCharsets.ISO_8859_1);
}
@Override
public AiResourceContent download(UUID resourceId, SecurityUser user) {
JsonNode content = tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(),
Base64.getDecoder().decode(content.path("data").asText()));
}
@Override
public void delete(UUID resourceId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
}
}

3
application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java

@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID;
public interface AiSolutionService {
@ -16,7 +17,7 @@ public interface AiSolutionService {
JsonNode getSolutions(SecurityUser user);
JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user);
JsonNode chat(UUID solutionId, SolutionStep step, String message, List<UUID> resources, SecurityUser user);
JsonNode createSolution(UUID solutionId, SecurityUser user);

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

@ -4,8 +4,12 @@ package org.thingsboard.server.service.ai.solution;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
@ -18,6 +22,7 @@ import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID;
@Service
@ -47,9 +52,14 @@ public class DefaultAiSolutionService implements AiSolutionService {
}
@Override
public JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user) {
public JsonNode chat(UUID solutionId, SolutionStep step, String message, List<UUID> resources, SecurityUser user) {
String text = StringUtils.defaultString(message);
List<UUID> attached = CollectionsUtil.isEmpty(resources) ? null : resources;
if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message)), user, tokenProvider), user);
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
}
@Override

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

@ -83,11 +83,11 @@ class ChannelTbAiOperations {
static TbAiResponse toResponse(OperationResult result) {
TbAiResponse response;
if (result.isSuccess()) {
response = TbAiResponse.builder().success(true).value(result.body()).build();
response = TbAiResponse.builder().success(true).status(result.status()).value(result.body()).build();
} else {
JsonNode message = result.body() != null ? result.body().get("message") : null;
String error = message != null && message.isTextual() ? message.asText() : reasonPhrase(result.status());
response = TbAiResponse.builder().success(false).error(error).build();
response = TbAiResponse.builder().success(false).status(result.status()).error(error).build();
}
response.setCreditsUsed(result.creditsUsed());
return response;

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

@ -121,6 +121,10 @@ public abstract class AbstractAiControllerTest extends AbstractControllerTest {
return TbAiClient.TbAiResponse.builder().success(false).error(error).build();
}
protected static TbAiClient.TbAiResponse failure(int status, String error) {
return TbAiClient.TbAiResponse.builder().success(false).status(status).error(error).build();
}
protected static ObjectNode chatMessage(String from, String content) {
return JacksonUtil.newObjectNode()
.put("from", from)

224
application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java

@ -0,0 +1,224 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ResourceOperationRequest;
import org.thingsboard.ai.common.channel.ResourceUploadRequest;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
public class AiResourceControllerTest extends AbstractAiControllerTest {
private static final byte[] PNG = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==");
@Test
public void shouldForwardTheFileBase64Encoded_whenUploadingAResource() throws Exception {
// GIVEN
loginTenantAdmin();
UUID resourceId = UUID.randomUUID();
ObjectNode info = resourceInfo(resourceId, "chart.png", "image/png", PNG.length);
var request = new ResourceUploadRequest("chart.png", "image/png", Base64.getEncoder().encodeToString(PNG));
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(5 * 1024 * 1024)));
givenOperation(ChannelProtocol.RESOURCE_UPLOAD, request, success(info));
// WHEN
JsonNode result = readResponse(upload("chart.png", "image/png", PNG).andExpect(status().isCreated()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(info);
TbAiTurnContext context = verifyOperation(ChannelProtocol.RESOURCE_UPLOAD, request);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
public void shouldRejectAFileOverTheAiServiceLimit_withoutUploadingIt() throws Exception {
// GIVEN
loginTenantAdmin();
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(1024)));
// WHEN
upload("huge.png", "image/png", new byte[1025])
.andExpect(status().isBadRequest())
.andExpect(statusReason(equalTo("The file is too large: huge.png")));
// THEN
verify(tbAiOperations, never()).execute(argThat(operation -> operation != null && ChannelProtocol.RESOURCE_UPLOAD.equals(operation.type())),
any(TbAiTurnContext.class));
}
static JsonNode limits(long maxSize) {
return JacksonUtil.newObjectNode().put("maxSize", maxSize).put("maxPerMessage", 5);
}
@Test
public void shouldServeTheFileWithItsTypeAndName_whenDownloadingAResource() throws Exception {
// GIVEN
loginTenantAdmin();
UUID resourceId = UUID.randomUUID();
ObjectNode content = JacksonUtil.newObjectNode()
.put("name", "chart.png")
.put("mediaType", "image/png")
.put("data", Base64.getEncoder().encodeToString(PNG));
givenOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId), success(content));
// WHEN
MvcResult result = doGet("/api/ai/resources/" + resourceId).andExpect(status().isOk()).andReturn();
// THEN
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(PNG);
assertThat(result.getResponse().getContentType()).isEqualTo("image/png");
assertThat(result.getResponse().getHeader(HttpHeaders.CONTENT_DISPOSITION)).isEqualTo("attachment; filename=\"chart.png\"");
assertThat(result.getResponse().getHeader("X-Content-Type-Options")).isEqualTo("nosniff");
}
@Test
public void shouldDeleteAnUnsentResource() throws Exception {
// GIVEN
loginTenantAdmin();
UUID resourceId = UUID.randomUUID();
givenOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId), success());
// WHEN
doDelete("/api/ai/resources/" + resourceId).andExpect(status().isNoContent());
// THEN
verifyOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId));
}
@Test
public void shouldKeepTheAiServiceStatus_whenAResourceIsMissingOrInvalid() throws Exception {
// GIVEN
loginTenantAdmin();
UUID resourceId = UUID.randomUUID();
givenOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId), failure(404, "Resource not found"));
givenOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId), failure(404, "Resource not found or already sent"));
// WHEN
MvcResult download = doGet("/api/ai/resources/" + resourceId).andReturn();
MvcResult delete = doDelete("/api/ai/resources/" + resourceId).andReturn();
// THEN
assertThat(download.getResponse().getStatus()).isEqualTo(404);
assertThat(delete.getResponse().getStatus()).isEqualTo(404);
assertThat(delete.getResponse().getContentAsString()).contains("Resource not found or already sent");
}
@Test
public void shouldReturnTheAcceptedFiles_whenGettingTheConfig() throws Exception {
// GIVEN
loginTenantAdmin();
JsonNode limits = JacksonUtil.toJsonNode("""
{"maxSize": 5242880, "maxPerMessage": 5, "mediaTypes": ["image/png"], "extensions": [".png"]}
""");
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits));
// WHEN
JsonNode result = doGet("/api/ai/resources/config", JsonNode.class);
// THEN
assertThat(result).isEqualTo(limits);
}
@Test
public void shouldSendTheAttachedResources_whenSendingASolutionMessage() throws Exception {
// GIVEN
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
UUID resourceId = UUID.randomUUID();
var request = new SolutionChatRequest(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, "Like this", List.of(resourceId));
ObjectNode solution = JacksonUtil.newObjectNode().put("id", solutionId.toString());
givenOperation(ChannelProtocol.SOLUTION_CHAT, request, success(solution));
// WHEN
JsonNode result = readResponse(solutionMessage(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, """
{"message": "Like this", "resources": ["%s"]}
""".formatted(resourceId)).andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
verifyOperation(ChannelProtocol.SOLUTION_CHAT, request);
}
@Test
public void shouldRejectASolutionMessage_whenItHasNeitherTextNorFiles() throws Exception {
// GIVEN
loginTenantAdmin();
// WHEN
solutionMessage(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, """
{"message": " ", "resources": []}
""")
.andExpect(status().isBadRequest())
.andExpect(statusReason(equalTo("Message cannot be blank")));
// THEN
verifyNoAiCalls();
}
@Test
public void shouldReturnForbiddenAndNotCallClient_whenCustomerUserUploads() throws Exception {
// GIVEN
loginCustomerUser();
// WHEN
upload("chart.png", "image/png", PNG)
.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermission)));
// THEN
verifyNoAiCalls();
}
private ResultActions upload(String name, String mediaType, byte[] content) throws Exception {
var request = MockMvcRequestBuilders.multipart(HttpMethod.POST, "/api/ai/resources")
.file(new MockMultipartFile("file", name, mediaType, content));
setJwtToken(request);
return mockMvc.perform(request);
}
private ResultActions solutionMessage(UUID solutionId, SolutionStep step, String body) throws Exception {
var request = post("/api/ai/solution/" + solutionId + "/" + step + "/messages")
.contentType(MediaType.APPLICATION_JSON)
.content(body.getBytes(StandardCharsets.UTF_8));
setJwtToken(request);
return mockMvc.perform(request);
}
private static ObjectNode resourceInfo(UUID id, String name, String mediaType, int size) {
return JacksonUtil.newObjectNode()
.put("id", id.toString())
.put("name", name)
.put("mediaType", mediaType)
.put("size", size);
}
}

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

@ -9,6 +9,7 @@ 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.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
@ -168,6 +169,22 @@ class DefaultTbAiServiceTest {
then(apiUsageReportClient).shouldHaveNoInteractions();
}
@ParameterizedTest
@CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, GENERAL", "404, ITEM_NOT_FOUND",
"409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, GENERAL", "500, GENERAL", "0, GENERAL"})
void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).status(status).error("The file is not UTF-8 text: notes.txt").build());
// WHEN
Throwable thrown = catchThrowable(() -> service.process(call, user, true));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("The file is not UTF-8 text: notes.txt");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(errorCode);
}
@Test
void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() {
// GIVEN

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

@ -22,6 +22,8 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
@ -29,10 +31,12 @@ import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@ -121,6 +125,17 @@ class DefaultAiSolutionServiceTest {
then(tbAiService).shouldHaveNoMoreInteractions();
}
@Test
void shouldRejectWithoutCallingTheAiService_whenAMessageHasNeitherTextNorFiles() {
// WHEN
Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, null, List.of(), user));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Message cannot be blank");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS);
then(tbAiService).shouldHaveNoInteractions();
}
@ParameterizedTest
@EnumSource(SolutionStep.class)
void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) {
@ -131,7 +146,7 @@ class DefaultAiSolutionServiceTest {
given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
// WHEN
JsonNode result = service.chat(solutionId, step, message, user);
JsonNode result = service.chat(solutionId, step, message, List.of(), user);
// THEN
assertThat(result).isSameAs(expectedResponse);

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

@ -224,6 +224,7 @@ class ChannelTbAiOperationsTest {
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getStatus()).isEqualTo(404);
assertThat(response.getError()).isEqualTo("Solution not found");
}

2
pom.xml

@ -63,7 +63,7 @@
<pkg.unixLogFolder>/var/log/${pkg.name}</pkg.unixLogFolder>
<pkg.installFolder>/usr/share/${pkg.name}</pkg.installFolder>
<pkg.controlScriptsFolder>control</pkg.controlScriptsFolder>
<thingsboard.ai.version>2.1.9-SNAPSHOT</thingsboard.ai.version>
<thingsboard.ai.version>2.1.10-SNAPSHOT</thingsboard.ai.version>
<thingsboard.client.version>4.4.0</thingsboard.client.version>
<spring-boot.version>3.5.15</spring-boot.version>
<!-- Pins spring-boot-test to 3.5.13: the ImportsContextCustomizer change in 3.5.14 causes "Duplicate spy

218
ui-ngx/src/app/core/http/ai-resource.service.ts

@ -0,0 +1,218 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpEvent, HttpEventType } from '@angular/common/http';
import { defaultHttpOptions, defaultHttpUploadOptions } from '@core/http/http-utils';
import { from, Observable, of, Subscription, throwError } from 'rxjs';
import { catchError, filter, finalize, map, shareReplay, switchMap } from 'rxjs/operators';
import { AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models';
export type AiResourceUploadEvent =
{ type: 'progress'; progress: number } |
{ type: 'done'; resource: AiResourceInfo };
interface CachedUrl {
url$: Observable<string>;
url?: string;
size: number;
dropped?: boolean;
}
const MAX_CONCURRENT_FETCHES = 3;
const MAX_CACHED_URLS = 40;
const MAX_CACHED_BYTES = 64 * 1024 * 1024;
@Injectable({
providedIn: 'root'
})
export class AiResourceService {
private config$: Observable<AiResourceConfig | null>;
private readonly urls = new Map<string, CachedUrl>();
private readonly waitingFetches: Array<() => void> = [];
private activeFetches = 0;
constructor(private http: HttpClient) {
}
getConfig(): Observable<AiResourceConfig | null> {
if (!this.config$) {
this.config$ = this.http.get<AiResourceConfig>('/api/ai/resources/config', defaultHttpOptions(true, true)).pipe(
catchError(() => {
this.config$ = null;
return of(null);
}),
shareReplay(1)
);
}
return this.config$;
}
upload(file: File): Observable<AiResourceUploadEvent> {
const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post<AiResourceInfo>('/api/ai/resources', formData, {
...defaultHttpUploadOptions(true, true),
observe: 'events',
reportProgress: true
}).pipe(
filter((event: HttpEvent<AiResourceInfo>) => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response),
map((event: HttpEvent<AiResourceInfo>): AiResourceUploadEvent => {
if (event.type === HttpEventType.UploadProgress) {
return {type: 'progress', progress: event.total ? Math.round(100 * event.loaded / event.total) : 0};
}
return {type: 'done', resource: (event as any).body as AiResourceInfo};
})
);
}
delete(resourceId: string): Observable<void> {
this.forget(resourceId);
return this.http.delete<void>(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true));
}
rememberUrl(resourceId: string, url: string, size: number): void {
this.forget(resourceId);
this.urls.set(resourceId, {url$: of(url), url, size});
this.evict(resourceId);
}
getUrl(resourceId: string): Observable<string> {
const cached = this.urls.get(resourceId);
if (cached) {
this.urls.delete(resourceId);
this.urls.set(resourceId, cached);
return cached.url$;
}
const entry: CachedUrl = {url$: null, size: 0};
entry.url$ = this.fetch(resourceId).pipe(
map(blob => {
const url = URL.createObjectURL(blob);
if (entry.dropped) {
setTimeout(() => URL.revokeObjectURL(url));
} else {
entry.url = url;
entry.size = blob.size;
this.evict(resourceId);
}
return url;
}),
catchError(error => {
if (this.urls.get(resourceId) === entry) {
this.urls.delete(resourceId);
}
throw error;
}),
shareReplay(1)
);
this.urls.set(resourceId, entry);
return entry.url$;
}
download(resource: AiResourceInfo): Observable<void> {
const cachedUrl = this.urls.get(resource.id)?.url;
if (cachedUrl) {
this.save(cachedUrl, resource.name);
return of(undefined);
}
return this.fetch(resource.id).pipe(
map(blob => {
const url = URL.createObjectURL(blob);
this.save(url, resource.name);
setTimeout(() => URL.revokeObjectURL(url));
})
);
}
private save(url: string, name: string): void {
const link = document.createElement('a');
link.href = url;
link.download = name;
document.body.appendChild(link);
link.click();
link.remove();
}
private fetch(resourceId: string): Observable<Blob> {
const request$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe(
catchError(error => this.readErrorBody(error))
);
return new Observable<Blob>(subscriber => {
let subscription: Subscription;
let finished = false;
const finish = () => {
if (!finished) {
finished = true;
this.activeFetches--;
this.waitingFetches.shift()?.();
}
};
const start = () => {
this.activeFetches++;
subscription = request$.pipe(finalize(finish)).subscribe(subscriber);
};
if (this.activeFetches < MAX_CONCURRENT_FETCHES) {
start();
} else {
this.waitingFetches.push(start);
}
return () => {
const index = this.waitingFetches.indexOf(start);
if (index >= 0) {
this.waitingFetches.splice(index, 1);
}
subscription?.unsubscribe();
};
});
}
private readErrorBody(error: any): Observable<never> {
if (!(error instanceof HttpErrorResponse) || !(error.error instanceof Blob)) {
return throwError(() => error);
}
return from(error.error.text()).pipe(
catchError(() => of('')),
switchMap(text => throwError(() => new HttpErrorResponse({
error: text || null,
headers: error.headers,
status: error.status,
statusText: error.statusText,
url: error.url ?? undefined
})))
);
}
private forget(resourceId: string): void {
const entry = this.urls.get(resourceId);
if (entry) {
this.urls.delete(resourceId);
this.release(entry);
}
}
private release(entry: CachedUrl): void {
entry.dropped = true;
if (entry.url) {
URL.revokeObjectURL(entry.url);
}
}
private evict(keep: string): void {
let bytes = 0;
this.urls.forEach(entry => bytes += entry.size);
for (const [resourceId, entry] of this.urls) {
if (this.urls.size <= MAX_CACHED_URLS && bytes <= MAX_CACHED_BYTES) {
break;
}
if (resourceId !== keep && entry.url) {
this.urls.delete(resourceId);
bytes -= entry.size;
this.release(entry);
}
}
}
}

6
ui-ngx/src/app/core/http/solutions-creator.service.ts

@ -39,8 +39,10 @@ export class SolutionsCreatorService {
return this.http.post<SolutionCreatorInfo>(`/api/ai/solution/${solutionId}/create`, '', defaultHttpOptionsFromConfig(config));
}
public chatSolution(solutionId: string, step: SolutionStep, msg: string, config?: RequestConfig): Observable<SolutionCreatorInfo> {
return this.http.post<SolutionCreatorInfo>(`/api/ai/solution/${solutionId}/${step}/chat`, msg, defaultHttpOptionsFromConfig(config));
public chatSolution(solutionId: string, step: SolutionStep, msg: string, config?: RequestConfig,
resources: string[] = []): Observable<SolutionCreatorInfo> {
return this.http.post<SolutionCreatorInfo>(`/api/ai/solution/${solutionId}/${step}/messages`,
{message: msg, resources}, defaultHttpOptionsFromConfig(config));
}
public updateSolutionData(solutionId: string, dataKey: SolutionDataKey, msg: SolutionDataValues, config?: RequestConfig): Observable<SolutionCreatorInfo> {

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

@ -4,7 +4,7 @@
SPDX-License-Identifier: BUSL-1.1
-->
<div class="ai-assistant-container relative"
<div #chatContainer class="ai-assistant-container relative"
[class.fill]="panelService.detailsOpen() || !!panelService.config()?.fill"
[class.details-open]="panelService.detailsOpen()">
<div class="ai-assistant-header">
@ -69,7 +69,8 @@
[additionalStyles]="['.tb-markdown-view p, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5, .tb-markdown-view h6, .tb-markdown-view div.code-wrapper {padding-left: 0 !important;}' +
'.tb-markdown-view ol {padding-inline-start: 30px;} .tb-markdown-view ul{padding-left: 28px;padding-right:0}'
]"
(approvalAction)="onApprovalAction($event)">
(approvalAction)="onApprovalAction($event)"
(resourceError)="showErrorMessage($event)">
</tb-ai-chat-messages>
</div>
} @else {
@ -86,22 +87,22 @@
</div>
</div>
}
<div class="flex w-full flex-col items-center gap-3">
@if (!messages().length && promptExamples().length) {
<div class="example-chips">
@for (example of promptExamples(); track example.message) {
<button type="button" mat-stroked-button class="example-chip" (click)="useExample(example)">
{{ example.label }}
</button>
}
</div>
}
<tb-ai-prompt-input
class="flex"
[placeholder]="activePlaceholder()"
[loading]="loading()"
(messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input>
</div>
@if (!messages().length && promptExamples().length) {
<div class="example-chips">
@for (example of promptExamples(); track example.message) {
<button type="button" mat-stroked-button class="example-chip" (click)="useExample(example)">
{{ example.label }}
</button>
}
</div>
}
</div>
<tb-ai-prompt-input
class="ai-assistant-composer"
[docked]="true"
[placeholder]="activePlaceholder()"
[loading]="loading()"
[dropZone]="chatContainer"
(messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input>
</div>

7
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss

@ -36,6 +36,7 @@
flex: 1;
min-height: 0;
width: 464px;
overflow: hidden;
&.fill {
margin: 0;
@ -47,6 +48,10 @@
}
}
.ai-assistant-composer {
flex: none;
}
.ai-assistant-header {
display: flex;
align-items: center;
@ -70,7 +75,7 @@
display: flex;
overflow: hidden;
flex: 1;
padding: 0 24px 24px;
padding: 0 24px 16px;
gap: 16px;
flex-direction: column;

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

@ -14,13 +14,14 @@ import {
ViewChild
} from '@angular/core';
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 { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs';
import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { AiChatService } from '@core/http/ai-chat.service';
import {
AiAssistantPromptExample,
AiChatClientContext,
AiPromptMessage,
ApprovalResult,
ChatEvent,
ChatInfo,
@ -183,9 +184,14 @@ export class AiAssistantPanelComponent implements OnInit {
ngOnInit() {
this.loadChat$.pipe(
switchMap(id => {
return this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true});
}),
switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe(
catchError(err => {
this.messages.set([]);
this.completedExecutions.set({});
setTimeout(() => this.showErrorMessage(err), 0);
return EMPTY;
})
)),
takeUntilDestroyed(this.destroyRef)
).subscribe(messages => {
this.showHistory(messages);
@ -235,10 +241,12 @@ export class AiAssistantPanelComponent implements OnInit {
this.promptInput?.setValue(example.message);
}
sendMsgFromUser(msg: string): void {
const userMessage: ChatMessage = {from: 'USER', content: msg};
sendMsgFromUser(prompt: AiPromptMessage): void {
const userMessage: ChatMessage = prompt.resources.length
? {from: 'USER', content: prompt.message, resources: prompt.resources}
: {from: 'USER', content: prompt.message};
this.messages.update(list => [...list, userMessage]);
this.sendMessage(msg).subscribe({
this.sendMessage(prompt).subscribe({
error: (err) => {
if (this.isConnectionLost(err) && this.chatId()) {
this.showErrorToast(this.translate.instant('ai-assistant.connection-lost'));
@ -351,7 +359,7 @@ export class AiAssistantPanelComponent implements OnInit {
}
}
private sendMessage(msg: string): Observable<ChatEvent> {
private sendMessage(prompt: AiPromptMessage): Observable<ChatEvent> {
this.initLoadingState();
this.sessionAffectedEntities = [];
this.messageCancelled = false;
@ -368,9 +376,12 @@ export class AiAssistantPanelComponent implements OnInit {
);
const request: SendChatMessageRequest = {
message: msg,
message: prompt.message,
clientContext: this.resolveClientContextToSend()
};
if (prompt.resources.length) {
request.resources = prompt.resources.map(resource => resource.id);
}
return startOrContinue$.pipe(
switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})),
@ -526,7 +537,7 @@ export class AiAssistantPanelComponent implements OnInit {
this.loading.set(false);
}
private showErrorMessage(error: any): void {
showErrorMessage(error: any): void {
const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined;
const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message;
this.showErrorToast(message);

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

@ -0,0 +1,32 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<mat-toolbar class="flex items-center gap-2">
<h2 class="preview-title">{{ data.resource.name }}</h2>
<span class="flex-1"></span>
<button mat-icon-button type="button" (click)="download()"
[matTooltip]="'action.download' | translate" matTooltipPosition="above">
<mat-icon>download</mat-icon>
</button>
<button mat-icon-button type="button" (click)="close()"
[matTooltip]="'action.close' | translate" matTooltipPosition="above">
<mat-icon>close</mat-icon>
</button>
</mat-toolbar>
<div mat-dialog-content class="preview-content" tb-toast toastTarget="aiAttachmentPreview">
@if (preview$ | async; as preview) {
@if (preview.url) {
<img [src]="preview.url" [alt]="data.resource.name">
} @else {
<div class="preview-error">
<mat-icon>broken_image</mat-icon>
<span>{{ preview.error }}</span>
</div>
}
} @else {
<mat-progress-spinner diameter="40" mode="indeterminate"></mat-progress-spinner>
}
</div>

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

@ -0,0 +1,50 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
:host {
display: flex;
flex-direction: column;
min-width: min(360px, 90vw);
max-height: 90vh;
.preview-title {
margin: 0;
font-size: 16px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.preview-content {
display: flex;
align-items: center;
justify-content: center;
padding: 0 16px 16px;
max-height: calc(90vh - 64px);
overflow: auto;
img {
max-width: 100%;
max-height: calc(90vh - 96px);
object-fit: contain;
border-radius: 8px;
}
.preview-error {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 32px 16px;
max-width: 360px;
color: rgba(0, 0, 0, 0.54);
text-align: center;
mat-icon {
width: 40px;
height: 40px;
font-size: 40px;
color: rgba(0, 0, 0, 0.38);
}
}
}
}

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

@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, Inject, SecurityContext } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { DomSanitizer } from '@angular/platform-browser';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { ActionNotificationShow } from '@core/notification/notification.actions';
import { aiServerMessage } from '@home/components/ai/ai-attachment.models';
import { AiResourceService } from '@core/http/ai-resource.service';
import { AiResourceInfo } from '@shared/models/ai-chat.models';
export interface AiAttachmentPreviewDialogData {
resource: AiResourceInfo;
}
interface AiAttachmentPreview {
url?: string;
error?: string;
}
@Component({
selector: 'tb-ai-attachment-preview-dialog',
templateUrl: './ai-attachment-preview-dialog.component.html',
styleUrls: ['./ai-attachment-preview-dialog.component.scss'],
standalone: false
})
export class AiAttachmentPreviewDialogComponent extends DialogComponent<AiAttachmentPreviewDialogComponent> {
readonly preview$: Observable<AiAttachmentPreview>;
constructor(protected store: Store<AppState>,
protected router: Router,
public dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData,
private aiResourceService: AiResourceService,
private translate: TranslateService,
private sanitizer: DomSanitizer) {
super(store, router, dialogRef);
this.preview$ = this.aiResourceService.getUrl(data.resource.id).pipe(
map(url => ({url})),
catchError(error => of({error: this.errorMessage(error)}))
);
}
download(): void {
this.aiResourceService.download(this.data.resource).subscribe({
error: error => this.store.dispatch(new ActionNotificationShow({
message: this.errorMessage(error),
target: 'aiAttachmentPreview',
modern: true,
type: 'error',
verticalPosition: 'bottom',
horizontalPosition: 'center'
}))
});
}
close(): void {
this.dialogRef.close();
}
private errorMessage(error: unknown): string {
const message = aiServerMessage(error);
return message ? this.sanitizer.sanitize(SecurityContext.HTML, message) ?? message : this.translate.instant('ai-assistant.attachment-load-failed');
}
}

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

@ -0,0 +1,189 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { HttpErrorResponse } from '@angular/common/http';
import { AI_IMAGE_MEDIA_TYPES } from '@shared/models/ai-chat.models';
const MAX_IMAGE_SIDE = 2560;
const MIN_SVG_SIDE = 1024;
const SVG_MEDIA_TYPE = 'image/svg+xml';
const SVG_UNITS: Record<string, number> = {'': 1, px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4};
export const AI_SVG_EXTENSION = '.svg';
export interface AiAttachmentKind {
icon: string;
label: string;
}
export const aiAttachmentKind = (mediaType: string, name: string): AiAttachmentKind => {
const extension = name.split('.').pop()?.toLowerCase();
if (mediaType?.startsWith('image/')) {
return {icon: 'image', label: 'ai-assistant.file-kind.image'};
}
if (mediaType === 'application/pdf' || extension === 'pdf') {
return {icon: 'picture_as_pdf', label: 'ai-assistant.file-kind.pdf'};
}
if (extension === 'xlsx' || extension === 'csv') {
return {icon: 'table_chart', label: 'ai-assistant.file-kind.table'};
}
if (extension === 'docx') {
return {icon: 'description', label: 'ai-assistant.file-kind.document'};
}
if (extension === 'pptx') {
return {icon: 'slideshow', label: 'ai-assistant.file-kind.slides'};
}
if (extension === 'json') {
return {icon: 'data_object', label: 'ai-assistant.file-kind.json'};
}
if (['txt', 'log', 'md', 'xml', 'yaml', 'yml', 'html', 'htm'].includes(extension)) {
return {icon: 'description', label: 'ai-assistant.file-kind.text'};
}
return {icon: 'attach_file', label: 'ai-assistant.file-kind.file'};
};
export const formatAiFileSize = (bytes: number): string => bytes >= 1048576
? (bytes / 1048576).toFixed(1).replace(/\.0$/, '') + ' MB'
: Math.max(1, Math.round(bytes / 1024)) + ' KB';
export const aiAttachmentExtension = (name: string): string => {
const dot = name.lastIndexOf('.');
return dot > 0 ? name.substring(dot + 1).toUpperCase() : '';
};
export const isAiSvg = (file: File): boolean => file.type === SVG_MEDIA_TYPE || file.name.toLowerCase().endsWith(AI_SVG_EXTENSION);
export const isAiAttachmentAccepted = (file: File, extensions: string[]): boolean => {
const name = file.name.toLowerCase();
return isAiSvg(file) || extensions.some(extension => name.endsWith(extension.toLowerCase()));
};
export const namePastedImage = (file: File): File => {
if (!AI_IMAGE_MEDIA_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) {
return file;
}
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').substring(0, 15);
const extension = file.type === 'image/jpeg' ? 'jpg' : file.type.split('/')[1];
return new File([file], `screenshot-${stamp}.${extension}`, {type: file.type, lastModified: file.lastModified});
};
const loadImage = (file: File): Promise<HTMLImageElement> => new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
URL.revokeObjectURL(url);
resolve(image);
};
image.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Image could not be decoded'));
};
image.src = url;
});
const encode = (canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> => new Promise((resolve, reject) =>
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Image could not be encoded')), type, quality));
export const fitAiImage = async (file: File, maxSize: number): Promise<File> => {
if (!AI_IMAGE_MEDIA_TYPES.includes(file.type)) {
return file;
}
let image: HTMLImageElement;
try {
image = await loadImage(file);
} catch {
return file;
}
const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(image.naturalWidth, image.naturalHeight));
if (scale === 1 && file.size <= maxSize) {
return file;
}
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale));
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale));
const context = canvas.getContext('2d');
if (file.type === 'image/jpeg') {
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.drawImage(image, 0, 0, canvas.width, canvas.height);
let blob = await encode(canvas, file.type, 0.92);
let type = file.type;
if (blob.size > maxSize) {
context.globalCompositeOperation = 'destination-over';
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
blob = await encode(canvas, 'image/jpeg', 0.85);
type = 'image/jpeg';
}
if (blob.size >= file.size && scale === 1) {
return file;
}
const base = file.name.replace(/\.[^.]+$/, '');
const name = type === file.type ? file.name : `${base}.jpg`;
return new File([blob], name, {type, lastModified: file.lastModified});
};
const svgLength = (value: string | null): number | null => {
const match = value?.trim().match(/^([0-9]*\.?[0-9]+(?:e[-+]?[0-9]+)?)\s*(px|pt|pc|in|cm|mm)?$/i);
const length = match ? parseFloat(match[1]) * SVG_UNITS[(match[2] ?? '').toLowerCase()] : NaN;
return length > 0 ? length : null;
};
export const svgToAiImage = async (file: File, maxSize: number): Promise<File> => {
const document = new DOMParser().parseFromString(await file.text(), SVG_MEDIA_TYPE);
const svg = document.documentElement;
if (svg.localName !== 'svg' || document.getElementsByTagName('parsererror').length) {
throw new Error('Not an SVG image');
}
Array.from(document.getElementsByTagNameNS('*', 'foreignObject')).forEach(node => node.remove());
const viewBox = (svg.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number);
const hasViewBox = viewBox.length === 4 && viewBox[2] > 0 && viewBox[3] > 0;
let width = svgLength(svg.getAttribute('width')) ?? (hasViewBox ? viewBox[2] : null);
let height = svgLength(svg.getAttribute('height')) ?? (hasViewBox ? viewBox[3] : null);
if (!width || !height) {
width = width ?? height ?? MIN_SVG_SIDE;
height = height ?? width;
}
if (!hasViewBox) {
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
}
const scale = Math.min(MAX_IMAGE_SIDE / Math.max(width, height), Math.max(1, MIN_SVG_SIDE / Math.max(width, height)));
const canvas = window.document.createElement('canvas');
canvas.width = Math.max(1, Math.round(width * scale));
canvas.height = Math.max(1, Math.round(height * scale));
svg.setAttribute('width', String(canvas.width));
svg.setAttribute('height', String(canvas.height));
const image = await loadImage(new File([new XMLSerializer().serializeToString(document)], file.name, {type: SVG_MEDIA_TYPE}));
const context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
let blob = await encode(canvas, 'image/png');
let type = 'image/png';
if (blob.size > maxSize) {
blob = await encode(canvas, 'image/jpeg', 0.85);
type = 'image/jpeg';
}
const base = file.name.replace(/\.[^.]+$/, '');
return new File([blob], `${base}.${type === 'image/png' ? 'png' : 'jpg'}`, {type, lastModified: file.lastModified});
};
export function aiServerMessage(error: unknown): string | undefined {
if (!(error instanceof HttpErrorResponse)) {
return undefined;
}
let body: unknown = error.error;
if (typeof body === 'string') {
const text = body.trim();
if (!text || text.startsWith('<')) {
return undefined;
}
try {
body = JSON.parse(text);
} catch {
return text;
}
}
const message = body && typeof body === 'object' ? (body as {message?: unknown}).message : undefined;
return typeof message === 'string' && message.trim() ? message.trim() : undefined;
}

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

@ -0,0 +1,30 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="attachments">
@for (item of shown; track item.resource.id) {
<div class="attachment"
[class.image]="item.image"
[class.file]="!item.image"
[matTooltip]="item.resource.name"
matTooltipPosition="above"
(click)="open(item)">
@if (item.image) {
@if (item.url$ | async; as url) {
<img [src]="url" [alt]="item.resource.name">
} @else {
<mat-icon class="placeholder">image</mat-icon>
}
} @else {
<div class="file-icon"><mat-icon>{{ item.icon }}</mat-icon></div>
<div class="file-meta">
<span class="file-name">{{ item.resource.name }}</span>
<span class="file-info">{{ item.extension }}@if (item.extension) { · }{{ item.resource.size | fileSize }}</span>
</div>
}
</div>
}
</div>

101
ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss

@ -0,0 +1,101 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
:host {
display: block;
max-width: 100%;
.attachments {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: inherit;
}
.attachment {
position: relative;
display: flex;
align-items: center;
border-radius: 10px;
border: 1px solid rgba(0, 0, 0, 0.12);
background: #fff;
overflow: hidden;
flex: none;
cursor: pointer;
&:hover {
border-color: var(--tb-primary-500);
}
&.image {
width: 64px;
height: 64px;
justify-content: center;
background: rgba(0, 0, 0, 0.04);
img {
width: 100%;
height: 100%;
object-fit: cover;
}
.placeholder {
color: rgba(0, 0, 0, 0.38);
}
}
&.file {
gap: 8px;
height: 48px;
max-width: 220px;
padding: 0 12px 0 8px;
.file-icon {
display: flex;
align-items: center;
justify-content: center;
flex: none;
width: 32px;
height: 32px;
border-radius: 8px;
color: var(--tb-primary-500);
position: relative;
&:before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
background: var(--tb-primary-500);
opacity: 0.1;
}
mat-icon {
font-size: 20px;
width: 20px;
height: 20px;
}
}
.file-meta {
display: flex;
flex-direction: column;
min-width: 0;
line-height: 16px;
.file-name {
font-size: 13px;
color: rgba(0, 0, 0, 0.87);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-info {
font-size: 11px;
color: rgba(0, 0, 0, 0.54);
white-space: nowrap;
}
}
}
}
}

70
ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts

@ -0,0 +1,70 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models';
import { AiResourceService } from '@core/http/ai-resource.service';
import { aiAttachmentExtension, aiAttachmentKind } from '@home/components/ai/ai-attachment.models';
import {
AiAttachmentPreviewDialogComponent,
AiAttachmentPreviewDialogData
} from '@home/components/ai/ai-attachment-preview-dialog.component';
interface AiAttachmentItem {
resource: AiResourceInfo;
image: boolean;
icon: string;
extension: string;
url$?: Observable<string | null>;
}
@Component({
selector: 'tb-ai-attachments',
templateUrl: './ai-attachments.component.html',
styleUrls: ['./ai-attachments.component.scss'],
standalone: false
})
export class AiAttachmentsComponent implements OnChanges {
@Input() resources: AiResourceInfo[];
@Output() resourceError = new EventEmitter<any>();
shown: AiAttachmentItem[] = [];
constructor(private aiResourceService: AiResourceService,
private dialog: MatDialog) {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.resources) {
this.shown = (this.resources ?? []).map(resource => {
const image = isAiImageResource(resource);
return {
resource,
image,
icon: aiAttachmentKind(resource.mediaType, resource.name).icon,
extension: aiAttachmentExtension(resource.name),
url$: image ? this.aiResourceService.getUrl(resource.id).pipe(catchError(() => [null])) : undefined
};
});
}
}
open(item: AiAttachmentItem): void {
if (item.image) {
this.dialog.open<AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData>(AiAttachmentPreviewDialogComponent, {
panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'],
maxWidth: '92vw',
data: {resource: item.resource}
});
} else {
this.aiResourceService.download(item.resource).subscribe({
error: error => this.resourceError.emit(error)
});
}
}
}

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

@ -7,7 +7,13 @@
@for (msg of messages; track $index) {
@if (msg.from === 'USER') {
<div class="user">
<div class="msg">{{ msg.content }}</div>
@if (msg.resources?.length) {
<tb-ai-attachments class="user-attachments" [resources]="msg.resources"
(resourceError)="resourceError.emit($event)"></tb-ai-attachments>
}
@if (msg.content) {
<div class="msg">{{ msg.content }}</div>
}
</div>
} @else {
<div class="ai">

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

@ -15,7 +15,22 @@
.user {
display: flex;
justify-content: end;
flex-direction: column;
align-items: flex-end;
gap: 6px;
.user-attachments {
max-width: 80%;
::ng-deep .attachments {
justify-content: flex-end;
.attachment.image {
width: 120px;
height: 90px;
}
}
}
.msg {
max-width: 80%;

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

@ -19,6 +19,7 @@ export class AiChatMessagesComponent implements OnChanges {
@Input() completedExecutions: Record<string, ToolExecutionResult> = {};
@Input() autoApprove = false;
@Output() approvalAction = new EventEmitter<ApprovalResult>();
@Output() resourceError = new EventEmitter<any>();
waitApproval = false;

132
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html

@ -4,27 +4,113 @@
SPDX-License-Identifier: BUSL-1.1
-->
<div class="prompt-input">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="mr-10 flex-1">
<textarea
matInput
#textarea
cdkTextareaAutosize
rows="2"
#autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="2"
cdkAutosizeMaxRows="6"
[placeholder]="placeholder"
[formControl]="message"
(keydown.enter)="onEnter($event)">
</textarea>
</mat-form-field>
<button mat-icon-button
type="button"
color="primary"
class="tb-mat-24 send-button !size-8"
[disabled]="loading"
(click)="send()">
<mat-icon>send</mat-icon>
</button>
<div class="tb-ai-composer" [class.docked]="docked" [class.drop]="dragging()" [class.has-text]="hasText()">
@if (attachEnabled()) {
<input #fileInput type="file" hidden multiple [accept]="accept()" (change)="onFilesPicked($event)">
}
<div class="composer-field">
@if (attachments().length) {
<div class="composer-files">
@for (attachment of attachments(); track attachment.key) {
<span class="composer-file"
[class.up]="attachment.status === 'uploading'"
[class.bad]="attachment.status === 'error'">
@if (attachment.previewUrl && attachment.status !== 'error') {
<span class="file-pic" aria-hidden="true" [style.background-image]="'url(' + attachment.previewUrl + ')'"></span>
} @else {
<mat-icon class="tb-mat-18">{{ attachment.status === 'error' ? 'error_outline' : attachment.icon }}</mat-icon>
}
<span class="file-text">
<b>{{ attachment.name }}</b>
<small>{{ meta(attachment) }}</small>
</span>
@if (attachment.status === 'uploading') {
<i class="file-bar" [style.width.%]="attachment.progress"></i>
}
<button type="button" class="file-remove"
[attr.aria-label]="'ai-assistant.remove-file' | translate: {name: attachment.name}"
(click)="removeAttachment(attachment)">
<mat-icon class="tb-mat-16">close</mat-icon>
</button>
</span>
}
</div>
}
<div class="composer-row">
<span class="composer-chevron" aria-hidden="true"></span>
<textarea #textarea
rows="2"
spellcheck="false"
[attr.aria-label]="'ai-assistant.ask-the-assistant' | translate"
[placeholder]="placeholder"
[formControl]="message"
(input)="onInput()"
(paste)="onPaste($event)"
(keydown)="onKeydown($event)"></textarea>
<span class="composer-send-slot">
<button type="button" class="composer-send"
[class.fly]="flying()"
[disabled]="!canSend"
[attr.aria-label]="'ai-assistant.send' | translate"
tb-popover [tbAiTip]="sendTip"
(click)="send()">
<span class="return-glyph" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M20 4v7a4 4 0 0 1-4 4H4" pathLength="1"/><polyline points="9 10 4 15 9 20" pathLength="1"/></svg>
</span>
</button>
</span>
</div>
<div class="composer-foot">
@if (attachEnabled()) {
<button type="button" class="composer-tool composer-add"
[attr.aria-label]="'ai-assistant.add-files' | translate"
tb-popover [tbAiTip]="addTip"
(click)="openFilePicker()">
<mat-icon class="tb-mat-18">attach_file</mat-icon>
</button>
}
<span class="composer-spacer"></span>
<button type="button" class="composer-tool"
[attr.aria-label]="'ai-assistant.shortcuts' | translate"
tb-popover [tbAiTip]="keysTip"
[tipToggle]="true">
<mat-icon class="tb-mat-18">keyboard</mat-icon>
</button>
</div>
</div>
</div>
<ng-template #sendTip>
<div class="tb-ai-tip-body tip-mini">
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
</div>
</div>
</ng-template>
<ng-template #addTip>
<div class="tb-ai-tip-body">
<div class="tip-head"><b>{{ 'ai-assistant.add-files' | translate }}</b></div>
<p>{{ 'ai-assistant.add-files-text' | translate }}</p>
<p class="tip-sub">{{ 'ai-assistant.add-files-hint' | translate: {count: maxPerMessage(), size: maxSize()} }}</p>
</div>
</ng-template>
<ng-template #keysTip>
<div class="tb-ai-tip-body tip-keys">
<div class="tip-head"><b>{{ 'ai-assistant.shortcuts' | translate }}</b></div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.new-line' | translate }}</span>
<span class="tip-caps"><kbd>Shift</kbd><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.focus-composer' | translate }}</span>
<span class="tip-caps"><kbd>/</kbd></span>
</div>
</div>
</ng-template>

452
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss

@ -1,30 +1,454 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
$ai-teal-300: #4db6ac;
$ai-teal-400: #26a69a;
$ai-action: #00695c;
$ai-action-hover: #004d40;
$ai-focus: #00695c;
$ai-teal-700: #00796b;
$ink: rgba(0, 0, 0, 0.87);
$ink-54: rgba(0, 0, 0, 0.54);
$ink-38: rgba(0, 0, 0, 0.38);
$faint: rgba(0, 0, 0, 0.56);
$line: rgba(0, 0, 0, 0.12);
$line-soft: rgba(0, 0, 0, 0.05);
$crit: #d12730;
$font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
$chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 5l7 7-7 7'/%3E%3C/svg%3E";
:host {
display: block;
width: 100%;
}
.tb-ai-composer {
width: 100%;
font-family: $font;
letter-spacing: 0.25px;
text-align: left;
.prompt-input {
border-radius: 12px;
border: 1px solid rgba(0, 0, 0, 0.2);
background-color: #fff;
.composer-field {
position: relative;
display: flow-root;
background: #fff;
border: 1px solid transparent;
border-radius: 14px;
box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.04), 0 1px 2px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.08);
transition: border-color .18s ease, box-shadow .18s ease;
&:focus-within {
border-color: $ai-focus;
box-shadow: 0 0 0 1px $ai-focus, 0 8px 24px rgba(0, 105, 92, 0.12);
.composer-chevron {
color: $ai-focus;
}
}
}
&.drop .composer-field {
box-shadow: inset 0 0 0 2px $ai-teal-300;
background: color-mix(in srgb, $ai-action 4%, #fff);
}
.composer-files {
display: flex;
flex: 1;
--mat-form-field-outlined-outline-width: 0px;
--mat-form-field-outlined-focus-outline-width: 0px;
flex-wrap: wrap;
gap: 6px;
margin: 10px 12px 0 16px;
}
.composer-file {
position: relative;
display: inline-flex;
align-items: center;
gap: 10px;
max-width: 100%;
overflow: hidden;
padding: 6px 10px 6px 8px;
border: 1px solid $line;
border-radius: 8px;
background: #fff;
font-size: 13.5px;
line-height: 20px;
animation: composer-file-in .12s ease-out;
.send-button {
.mat-icon {
flex: none;
color: $ink-54;
}
.file-pic {
flex: none;
width: 32px;
height: 32px;
border-radius: 6px;
background: linear-gradient(135deg, #cfd8dc, #90a4ae) center / cover no-repeat;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06);
}
.file-text {
display: flex;
flex-direction: column;
min-width: 0;
overflow-wrap: anywhere;
b {
max-width: 240px;
overflow: hidden;
font-size: 13.5px;
font-weight: 500;
line-height: 18px;
color: $ink;
text-overflow: ellipsis;
white-space: nowrap;
}
small {
font-size: 12px;
line-height: 16px;
color: $faint;
}
}
.file-bar {
position: absolute;
right: 10px;
bottom: 10px;
left: 0;
bottom: 0;
height: 2px;
background: $ai-action;
transition: width .15s linear;
}
.file-remove {
flex: none;
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
margin-right: -4px;
padding: 0;
border: 0;
border-radius: 50%;
background: none;
color: $ink-54;
cursor: pointer;
&:hover {
background: rgba(0, 0, 0, 0.06);
color: $ink;
}
}
&.up small {
color: $ai-teal-700;
}
&.bad {
border-color: color-mix(in srgb, $crit 40%, transparent);
background: color-mix(in srgb, $crit 4%, #fff);
.mat-icon, small {
color: $crit;
}
}
}
.composer-row {
position: relative;
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px 0 8px 16px;
}
.composer-chevron {
--chevron: 18px;
display: flex;
flex: none;
align-items: center;
height: 24px;
margin: 4px 0 0 -2px;
color: $ai-action;
transition: color .18s ease;
&::before {
content: '';
width: var(--chevron);
height: var(--chevron);
background: currentColor;
mask: url($chevron) center / contain no-repeat;
}
}
textarea {
flex: 1;
min-width: 0;
min-height: 72px;
max-height: 240px;
margin: 4px 0 0;
padding: 0 58px 0 0;
border: 0;
outline: 0;
resize: none;
background: transparent;
font-family: $font;
font-size: 16px;
line-height: 24px;
letter-spacing: normal;
color: $ink;
caret-color: $ai-action;
tab-size: 2;
transition: height .12s ease;
&::placeholder {
color: $faint;
}
}
.composer-send-slot {
position: absolute;
right: 12px;
bottom: 12px;
display: inline-flex;
}
.composer-send {
position: relative;
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
padding: 0;
border: 0;
border-radius: 10px;
background: $ai-action;
color: #fff;
cursor: pointer;
transition: background-color .2s ease, color .2s ease, box-shadow .2s ease, transform .16s cubic-bezier(.2, 0, 0, 1);
&:hover:not(:disabled) {
background: $ai-action-hover;
.return-glyph polyline {
transform: scale(1.12);
}
}
&:active:not(:disabled) {
transform: scale(.92);
}
&:focus-visible {
outline: 2px solid $ai-focus;
outline-offset: 2px;
}
&:disabled {
background: rgba(0, 0, 0, 0.06);
color: $ink-38;
cursor: default;
}
&.fly .return-glyph polyline {
animation: composer-grow .32s cubic-bezier(.2, 0, 0, 1);
}
}
.return-glyph {
display: inline-flex;
width: 20px;
height: 20px;
svg {
width: 100%;
height: 100%;
overflow: visible;
fill: none;
stroke: currentColor;
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
}
polyline {
transform-box: fill-box;
transform-origin: 0 50%;
transition: transform .16s ease-out;
}
}
.composer-foot {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 2px;
padding: 2px 8px 6px 16px;
border-top: 1px solid $line-soft;
border-radius: 0 0 14px 14px;
font-size: 13px;
line-height: 18px;
color: rgba(0, 0, 0, 0.6);
}
.composer-spacer {
flex: 1;
}
.composer-tool {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
margin: 0;
padding: 0;
border: 0;
border-radius: 8px;
background: none;
color: $ink-54;
cursor: pointer;
transition: background-color .12s ease, color .12s ease;
&:hover, &[aria-describedby] {
background: $line-soft;
color: $ink;
}
&:focus-visible {
outline: 2px solid $ai-focus;
outline-offset: 1px;
color: $ink;
}
}
.composer-foot > .composer-add:first-child {
margin-left: -9px;
}
&.docked {
border-top: 1px solid $line;
background: #fff;
font-size: 14px;
line-height: 20px;
transition: border-top-color .18s ease;
&:focus-within {
border-top-color: $ai-focus;
}
.composer-field {
border: 0;
border-radius: 0;
box-shadow: none;
transition: box-shadow .18s ease;
&:focus-within {
box-shadow: inset 0 1px 0 $ai-focus;
}
}
&.drop .composer-field {
box-shadow: inset 0 0 0 2px $ai-teal-300;
}
.composer-files {
margin: 8px 8px 0 12px;
}
.composer-row {
gap: 6px;
padding: 6px 0 6px 12px;
}
.composer-chevron {
--chevron: 17px;
height: 22px;
}
textarea {
min-height: 44px;
max-height: 160px;
padding-right: 44px;
font-size: 14px;
line-height: 20px;
}
.composer-send-slot {
right: 8px;
bottom: 8px;
}
.composer-send {
width: 28px;
height: 28px;
border-radius: 8px;
}
.return-glyph {
width: 17px;
height: 17px;
svg {
stroke-width: 2.4;
}
}
.composer-foot {
flex-wrap: nowrap;
gap: 6px 8px;
padding: 2px 8px 6px 12px;
border-radius: 0;
font-size: 12px;
}
.composer-tool {
width: 28px;
height: 28px;
}
.composer-foot > .composer-add:first-child {
margin-left: -7.5px;
}
}
}
@keyframes composer-grow {
0% {
transform: none;
}
40% {
transform: scale(1.2);
}
100% {
transform: none;
}
}
:host::ng-deep {
.prompt-input {
.mdc-text-field--outlined {
padding-right: 8px;
@keyframes composer-file-in {
from {
opacity: 0;
transform: translateY(2px);
}
}
@media (prefers-reduced-motion: reduce) {
.tb-ai-composer {
.composer-file {
animation: none;
}
.composer-send .return-glyph polyline {
animation: none;
transition: none;
transform: none !important;
}
&.docked, .file-bar {
transition: none;
}
}
}

396
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts

@ -1,8 +1,59 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import {
AfterViewInit,
Component,
computed,
ElementRef,
EventEmitter,
HostListener,
inject,
Input,
OnChanges,
OnDestroy,
Output,
Renderer2,
signal,
SimpleChanges,
untracked,
ViewChild,
SecurityContext
} from '@angular/core';
import { FormControl } from '@angular/forms';
import { CdkTextareaAutosize } from '@angular/cdk/text-field';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subscription } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { DomSanitizer } from '@angular/platform-browser';
import { guid } from '@core/utils';
import { AiResourceService } from '@core/http/ai-resource.service';
import { AI_IMAGE_MEDIA_TYPES, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models';
import {
AI_SVG_EXTENSION,
aiAttachmentKind,
fitAiImage,
formatAiFileSize,
isAiAttachmentAccepted,
isAiSvg,
namePastedImage,
svgToAiImage,
aiServerMessage
} from '@home/components/ai/ai-attachment.models';
interface PendingAttachment {
key: string;
name: string;
size: number;
icon: string;
kind: string;
status: 'uploading' | 'ready' | 'error';
progress: number;
reason?: string;
previewUrl?: string;
resource?: AiResourceInfo;
upload?: Subscription;
}
const FLY_DURATION = 520;
@Component({
selector: 'tb-ai-prompt-input',
@ -10,40 +61,127 @@ import { CdkTextareaAutosize } from '@angular/cdk/text-field';
styleUrls: ['./ai-prompt-input.component.scss'],
standalone: false
})
export class AiPromptInputComponent {
export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestroy {
private aiResourceService = inject(AiResourceService);
private translate = inject(TranslateService);
private sanitizer = inject(DomSanitizer);
private renderer = inject(Renderer2);
private host = inject<ElementRef<HTMLElement>>(ElementRef);
@Input() placeholder = '';
@Input() loading: boolean;
@Output() messageSent = new EventEmitter<string>();
@Input() docked = false;
@Input() dropZone: HTMLElement;
@ViewChild('autosize') autosize!: CdkTextareaAutosize;
@Output() messageSent = new EventEmitter<AiPromptMessage>();
@ViewChild('textarea') textarea!: ElementRef<HTMLTextAreaElement>;
@ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
message = new FormControl<string>('');
onEnter(event: Event): void {
const ke = event as KeyboardEvent;
if (!ke.shiftKey) {
ke.preventDefault();
config = toSignal(this.aiResourceService.getConfig(), {initialValue: null as AiResourceConfig | null});
attachments = signal<PendingAttachment[]>([]);
attachEnabled = computed(() => !!this.config());
accept = computed(() => this.config() ? [...this.config().extensions, AI_SVG_EXTENSION].join(',') : '');
maxPerMessage = computed(() => this.config()?.maxPerMessage ?? 0);
maxSize = computed(() => formatAiFileSize(this.config()?.maxSize ?? 0));
uploading = computed(() => this.attachments().some(attachment => attachment.status === 'uploading'));
hasText = signal(false);
dragging = signal(false);
flying = signal(false);
private dropTarget: HTMLElement;
private dragDepth = 0;
private unlisten: Array<() => void> = [];
private flyTimer: ReturnType<typeof setTimeout>;
private destroyed = false;
get canSend(): boolean {
const ready = this.attachments().some(attachment => attachment.status === 'ready');
return !this.loading && !this.uploading() && (!!this.message.value?.trim() || ready);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.dropZone) {
this.listenForDrops(this.dropZone ?? this.host.nativeElement);
}
}
ngAfterViewInit(): void {
if (!this.dropTarget) {
this.listenForDrops(this.host.nativeElement);
}
setTimeout(() => this.resize());
}
ngOnDestroy(): void {
this.destroyed = true;
clearTimeout(this.flyTimer);
this.stopListening();
this.clearAttachments(true);
}
@HostListener('document:keydown', ['$event'])
onDocumentKeydown(event: KeyboardEvent): void {
if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey) {
return;
}
const target = event.target as HTMLElement;
if (target?.closest?.('input, textarea, select, [contenteditable]')) {
return;
}
const visible = Array.from(document.querySelectorAll<HTMLTextAreaElement>('.tb-ai-composer textarea'))
.filter(textarea => textarea.offsetParent);
const field = this.textarea?.nativeElement;
if (field && visible[visible.length - 1] === field) {
event.preventDefault();
field.focus();
field.selectionStart = field.selectionEnd = field.value.length;
}
}
onKeydown(event: KeyboardEvent): void {
if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) {
event.preventDefault();
this.send();
}
}
onInput(): void {
this.hasText.set(!!this.message.value);
this.resize();
}
send(): void {
const msg = this.message.value?.trim();
if (msg && !this.loading) {
this.reset();
this.messageSent.emit(msg);
const msg = this.message.value?.trim() ?? '';
const ready = this.attachments().filter(attachment => attachment.status === 'ready');
if (this.loading || this.uploading() || (!msg && !ready.length)) {
return;
}
this.fly();
this.clearText();
this.clearAttachments(false);
this.messageSent.emit({message: msg, resources: ready.map(attachment => attachment.resource)});
}
reset(): void {
this.message.reset('');
// Not autosize.reset(): it restores a height captured before the placeholder was known.
this.autosize?.resizeToFitContent(true);
this.clearText();
this.clearAttachments(true);
}
focus(): void {
@ -52,9 +190,233 @@ export class AiPromptInputComponent {
setValue(value: string): void {
this.message.setValue(value);
this.hasText.set(!!value);
setTimeout(() => {
this.textarea?.nativeElement.focus();
this.autosize?.resizeToFitContent(true);
this.resize();
});
}
openFilePicker(): void {
this.fileInput?.nativeElement.click();
}
onFilesPicked(event: Event): void {
const input = event.target as HTMLInputElement;
this.addFiles(Array.from(input.files ?? []));
input.value = '';
}
onPaste(event: ClipboardEvent): void {
const clipboard = event.clipboardData;
const files = Array.from(clipboard?.files ?? []);
if (files.length && !clipboard.types.includes('text/plain') && this.attachEnabled()) {
event.preventDefault();
this.addFiles(files.map(namePastedImage));
}
}
removeAttachment(attachment: PendingAttachment): void {
this.discard(attachment);
this.attachments.update(list => list.filter(candidate => candidate.key !== attachment.key));
}
meta(attachment: PendingAttachment): string {
if (attachment.status === 'error') {
return attachment.reason;
}
if (attachment.status === 'uploading') {
return this.translate.instant('ai-assistant.attachment-uploading', {progress: attachment.progress});
}
return `${this.translate.instant(attachment.kind)} · ${formatAiFileSize(attachment.size)}`;
}
addFiles(files: File[]): void {
const config = this.config();
if (!config || !files.length) {
return;
}
for (const file of files) {
const accepted = this.attachments().filter(attachment => attachment.status !== 'error').length;
if (accepted >= config.maxPerMessage) {
this.refuse(file, this.translate.instant('ai-assistant.attachment-over-limit', {count: config.maxPerMessage}));
} else if (!isAiAttachmentAccepted(file, config.extensions)) {
this.refuse(file, this.translate.instant('ai-assistant.attachment-unsupported'));
} else {
this.prepare(file, config);
}
}
}
private refuse(file: File, reason: string): void {
this.attachments.update(list => [...list, {
...this.describe(file, file.type),
status: 'error',
progress: 0,
reason
}]);
}
private describe(file: File, mediaType: string): Pick<PendingAttachment, 'key' | 'name' | 'size' | 'icon' | 'kind'> {
const kind = aiAttachmentKind(mediaType, file.name);
return {key: guid(), name: file.name, size: file.size, icon: kind.icon, kind: kind.label};
}
private async prepare(original: File, config: AiResourceConfig): Promise<void> {
const attachment: PendingAttachment = {
...this.describe(original, original.type || config.mediaTypes[0]),
status: 'uploading',
progress: 0
};
this.attachments.update(list => [...list, attachment]);
let file: File;
let failure: string;
if (isAiSvg(original)) {
try {
file = await svgToAiImage(original, config.maxSize);
} catch {
failure = this.translate.instant('ai-assistant.attachment-svg-failed');
}
} else {
try {
file = await fitAiImage(original, config.maxSize);
} catch {
file = original;
}
}
if (this.destroyed || !this.attachments().some(candidate => candidate.key === attachment.key)) {
return;
}
if (failure) {
this.patch(attachment.key, {status: 'error', reason: failure});
return;
}
if (file.size > config.maxSize) {
this.patch(attachment.key, {
status: 'error',
reason: this.translate.instant('ai-assistant.attachment-larger-than', {size: formatAiFileSize(config.maxSize)})
});
return;
}
this.startUpload(attachment.key, file, config);
}
private startUpload(key: string, file: File, config: AiResourceConfig): void {
const previewUrl = AI_IMAGE_MEDIA_TYPES.includes(file.type) ? URL.createObjectURL(file) : undefined;
this.patch(key, {...this.describe(file, file.type || config.mediaTypes[0]), key, previewUrl});
const upload = this.aiResourceService.upload(file).subscribe({
next: event => {
if (event.type === 'progress') {
this.patch(key, {progress: event.progress});
} else {
if (previewUrl) {
this.aiResourceService.rememberUrl(event.resource.id, previewUrl, file.size);
}
this.patch(key, {status: 'ready', resource: event.resource, progress: 100});
}
},
error: error => this.patch(key, {status: 'error', reason: this.errorMessage(error)})
});
this.patch(key, {upload});
}
private patch(key: string, changes: Partial<PendingAttachment>): void {
this.attachments.update(list => list.map(attachment => attachment.key === key ? {...attachment, ...changes} : attachment));
}
private fly(): void {
this.flying.set(false);
clearTimeout(this.flyTimer);
requestAnimationFrame(() => {
this.flying.set(true);
this.flyTimer = setTimeout(() => this.flying.set(false), FLY_DURATION);
});
}
private resize(): void {
const field = this.textarea?.nativeElement;
if (!field) {
return;
}
const cap = this.docked ? Math.min(160, Math.round(innerHeight * 0.3)) : Math.min(220, Math.round(innerHeight * 0.4));
field.style.height = 'auto';
field.style.height = Math.min(field.scrollHeight, cap) + 'px';
}
private clearText(): void {
this.message.reset('');
this.hasText.set(false);
setTimeout(() => this.resize());
}
private clearAttachments(discard: boolean): void {
const attachments = untracked(() => this.attachments());
if (!attachments.length) {
return;
}
attachments
.filter(attachment => discard || attachment.status !== 'ready')
.forEach(attachment => this.discard(attachment));
this.attachments.set([]);
}
private discard(attachment: PendingAttachment): void {
attachment.upload?.unsubscribe();
if (attachment.resource) {
this.aiResourceService.delete(attachment.resource.id).subscribe({error: () => {}});
}
if (attachment.previewUrl) {
URL.revokeObjectURL(attachment.previewUrl);
}
}
private errorMessage(error: unknown): string {
const message = aiServerMessage(error);
return message ? this.sanitizer.sanitize(SecurityContext.HTML, message) ?? message : this.translate.instant('ai-assistant.attachment-failed');
}
private listenForDrops(target: HTMLElement): void {
this.stopListening();
this.dropTarget = target;
const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
this.unlisten = [
this.renderer.listen(target, 'dragenter', (event: DragEvent) => {
if (!hasFiles(event) || !this.attachEnabled()) {
return;
}
event.preventDefault();
if (this.dragDepth++ === 0) {
this.dragging.set(true);
}
}),
this.renderer.listen(target, 'dragover', (event: DragEvent) => {
if (hasFiles(event) && this.attachEnabled()) {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
}
}),
this.renderer.listen(target, 'dragleave', (event: DragEvent) => {
if (hasFiles(event) && this.dragDepth > 0 && --this.dragDepth === 0) {
this.dragging.set(false);
}
}),
this.renderer.listen(target, 'drop', (event: DragEvent) => {
if (!hasFiles(event) || !this.attachEnabled()) {
return;
}
event.preventDefault();
this.dragDepth = 0;
this.dragging.set(false);
this.addFiles(Array.from(event.dataTransfer.files ?? []));
})
];
}
private stopListening(): void {
this.unlisten.forEach(unlisten => unlisten());
this.unlisten = [];
this.dragDepth = 0;
this.dragging.set(false);
}
}

118
ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts

@ -0,0 +1,118 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Directive, ElementRef, HostListener, inject, Input, OnDestroy, OnInit, Renderer2, TemplateRef } from '@angular/core';
import { Subscription } from 'rxjs';
import { TbPopoverDirective } from '@shared/components/popover.component';
const SHOW_DELAY = 0.35;
const HIDE_DELAY = 0.08;
const TIP_ID = 'tb-ai-tip';
const openTip: { current: AiTipDirective | null } = {current: null};
@Directive({
selector: '[tbAiTip]',
standalone: false
})
export class AiTipDirective implements OnInit, OnDestroy {
private popover = inject(TbPopoverDirective, {self: true});
private elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
@Input('tbAiTip') template: TemplateRef<void>;
@Input() tipToggle = false;
private pointerType: string;
private visibleSubscription: Subscription;
private unlistenKeydown: () => void;
private get trigger(): HTMLElement {
return this.elementRef.nativeElement;
}
ngOnInit(): void {
this.popover.content = this.template;
this.popover.trigger = 'hover';
this.popover.placement = ['top', 'topRight', 'topLeft', 'bottom', 'bottomRight', 'bottomLeft'];
this.popover.showCloseButton = false;
this.popover.mouseEnterDelay = SHOW_DELAY;
this.popover.mouseLeaveDelay = HIDE_DELAY;
this.popover.overlayClassName = 'tb-ai-tip';
this.visibleSubscription = this.popover.visibleChange.subscribe(visible => visible ? this.onShown() : this.onHidden());
}
ngOnDestroy(): void {
this.visibleSubscription?.unsubscribe();
this.onHidden();
}
@HostListener('pointerenter', ['$event'])
onPointerEnter(event: PointerEvent): void {
this.pointerType = event.pointerType;
const other = openTip.current !== this ? openTip.current : null;
this.popover.mouseEnterDelay = other ? 0 : SHOW_DELAY;
other?.popover.hide();
}
@HostListener('mouseenter', ['$event'])
onMouseEnter(event: MouseEvent): void {
if (this.pointerType === 'touch') {
event.stopImmediatePropagation();
}
}
@HostListener('focus')
onFocus(): void {
if (this.trigger.matches(':focus-visible')) {
this.popover.show();
}
}
@HostListener('blur')
onBlur(): void {
this.popover.hide();
}
@HostListener('click', ['$event'])
onClick(event: MouseEvent): void {
if (!this.tipToggle || this.popover.component?.visible) {
this.popover.hide();
return;
}
event.preventDefault();
this.popover.show();
}
private onShown(): void {
if (openTip.current !== this) {
openTip.current?.popover.hide();
}
openTip.current = this;
this.unlistenKeydown?.();
this.unlistenKeydown = this.renderer.listen('document', 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') {
this.popover.hide();
}
});
Promise.resolve().then(() => {
const pane = this.popover.component?.overlay?.overlayRef?.overlayElement;
const tip = pane?.querySelector('.tb-popover-inner');
if (openTip.current === this && tip) {
this.renderer.setStyle(pane, 'pointer-events', 'none');
tip.id = TIP_ID;
this.trigger.setAttribute('aria-describedby', TIP_ID);
}
});
}
private onHidden(): void {
if (openTip.current === this) {
openTip.current = null;
}
this.unlistenKeydown?.();
this.unlistenKeydown = null;
this.trigger.removeAttribute('aria-describedby');
}
}

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

@ -12,6 +12,9 @@ import { AiCreditsComponent } from '@home/components/ai/ai-credits.component';
import { AiCreditsPopupComponent } from '@home/components/ai/ai-credits-popup.component';
import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component';
import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component';
import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component';
import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component';
import { AiTipDirective } from '@home/components/ai/ai-tip.directive';
@NgModule({
declarations: [
@ -23,7 +26,10 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry
AiCreditsComponent,
AiCreditsPopupComponent,
AiLoadingModalComponent,
AiNoTelemetryModalComponent
AiNoTelemetryModalComponent,
AiAttachmentsComponent,
AiAttachmentPreviewDialogComponent,
AiTipDirective
],
imports: [
CommonModule,
@ -37,7 +43,8 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry
AiRenameDialogComponent,
AiCreditsComponent,
AiLoadingModalComponent,
AiNoTelemetryModalComponent
AiNoTelemetryModalComponent,
AiAttachmentsComponent
]
})
export class AiModule {}

59
ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts

@ -14,6 +14,10 @@ import { selectUserSettingsProperty } from '@core/auth/auth.selectors';
import { distinctUntilChanged, skip, take } from 'rxjs/operators';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { ActionPreferencesPutUserSettings } from '@core/auth/auth.actions';
import { HttpErrorResponse } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils';
import { ActionNotificationShow } from '@core/notification/notification.actions';
@Component({
selector: 'tb-solution-side-bar',
@ -41,6 +45,7 @@ export class SolutionSideBarComponent extends PageComponent implements OnInit {
private router: Router,
private route: ActivatedRoute,
protected store: Store<AppState>,
private sanitizer: DomSanitizer,
) {
super();
this.store.pipe(select(selectUserSettingsProperty('isSolutionSidebarExpanded'))).pipe(
@ -61,9 +66,10 @@ export class SolutionSideBarComponent extends PageComponent implements OnInit {
}
ngOnInit() {
this.solutionCreator.getSolutions({ignoreLoading: true}).subscribe((solutions) => {
this.solutions.set(solutions);
})
this.solutionCreator.getSolutions({ignoreLoading: true, ignoreErrors: true}).subscribe({
next: solutions => this.solutions.set(solutions),
error: error => this.showError(error)
});
}
toggleSidebar($event: Event): void {
@ -89,12 +95,15 @@ export class SolutionSideBarComponent extends PageComponent implements OnInit {
this.translate.instant('solution-creator.delete-solution-confirm')
).subscribe((value) => {
if (value) {
this.solutionCreator.deleteSolution(solution.id).subscribe(() => {
this.solutions.update(solutions => solutions.filter(s => s.id !== solution.id));
if (this.route.snapshot.queryParamMap.has('solutionId') && this.route.snapshot.queryParamMap.get('solutionId') === solution.id) {
this.router.navigate(['/ai-solution-creator']).then(() => {});
}
})
this.solutionCreator.deleteSolution(solution.id, {ignoreErrors: true}).subscribe({
next: () => {
this.solutions.update(solutions => solutions.filter(s => s.id !== solution.id));
if (this.route.snapshot.queryParamMap.has('solutionId') && this.route.snapshot.queryParamMap.get('solutionId') === solution.id) {
this.router.navigate(['/ai-solution-creator']).then(() => {});
}
},
error: error => this.showError(error)
});
}
})
}
@ -118,10 +127,13 @@ export class SolutionSideBarComponent extends PageComponent implements OnInit {
}
}).afterClosed().subscribe(newTitle => {
if (newTitle && newTitle !== solution.solutionTitle) {
this.solutionCreator.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(newTitle))
.subscribe(value => {
solution.solutionTitle = newTitle;
this.updatedSolution.next(value);
this.solutionCreator.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(newTitle), {ignoreErrors: true})
.subscribe({
next: value => {
solution.solutionTitle = newTitle;
this.updatedSolution.next(value);
},
error: error => this.showError(error)
});
}
});
@ -135,14 +147,29 @@ export class SolutionSideBarComponent extends PageComponent implements OnInit {
this.translate.instant('solution-creator.uninstall-solution-dialog-confirm')
).subscribe((value) => {
if (value) {
this.solutionCreator.uninstallSolution(solution.id, {ignoreErrors: true}).subscribe(() => {
this.updateSolutionField(solution, {installed: false});
this.installedChanged.emit({solutionId: solution.id, installed: false});
this.solutionCreator.uninstallSolution(solution.id, {ignoreErrors: true}).subscribe({
next: () => {
this.updateSolutionField(solution, {installed: false});
this.installedChanged.emit({solutionId: solution.id, installed: false});
},
error: error => this.showError(error)
});
}
});
}
private showError(error: unknown): void {
const responseType = isNotEmptyStr((error as {error?: unknown})?.error) ? 'text' : undefined;
this.store.dispatch(new ActionNotificationShow({
message: parseHttpErrorMessage(error as HttpErrorResponse, this.translate, responseType, this.sanitizer).message,
modern: true,
type: 'error',
target: 'solution-creator',
verticalPosition: 'top',
horizontalPosition: 'center'
}));
}
updateSolutionField(solution: SolutionInfo | {id: string}, fields: Partial<SolutionInfo>): void {
const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
this.solutions.update(solutions =>

6
ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html

@ -38,7 +38,7 @@
@switch (creatorStep()) {
@case ('chat') {
<div class="chat-container flex w-full flex-auto rounded-lg">
<div class="chat relative flex size-full flex-col items-center justify-end gap-3"
<div #chatArea class="chat relative flex size-full flex-col items-center justify-end gap-3"
[class.background]="isInitialEmpty()">
@if (isInitialEmpty()) {
<div class="welcome-content">
@ -57,7 +57,8 @@
<tb-ai-chat-messages
[messages]="messages()"
[loading]="loading()"
[loadingLongTime]="loadingLongTime()">
[loadingLongTime]="loadingLongTime()"
(resourceError)="showErrorMessage($event)">
<div loadingLongTime class="long-wait flex w-full flex-col items-center gap-6 rounded-xl">
<img [src]="loadingImage" alt="Loading">
<div class="flex flex-col items-center gap-1">
@ -72,6 +73,7 @@
<tb-ai-prompt-input
[placeholder]="activePlaceholder() | translate"
[loading]="loading()"
[dropZone]="chatArea"
(messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input>
@if (isInitialEmpty()) {

17
ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts

@ -16,6 +16,7 @@ import {
SolutionStepStatus
} from '@shared/models/solution-creator.models';
import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component';
import { AiPromptMessage } from '@shared/models/ai-chat.models';
import { SolutionsCreatorService } from '@core/http/solutions-creator.service';
import {
catchError,
@ -507,7 +508,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
startCreateSolution(key: string) {
const example = this.solutionExamples.find(ex => ex.key === key);
if (example) {
this.sendMsgFromUser(example.message);
this.sendMsgFromUser({message: example.message, resources: []});
}
}
@ -531,7 +532,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
}).afterClosed().subscribe(() => {});
}
private sendMessage(msg: string): Observable<SolutionCreatorInfo> {
private sendMessage(msg: string, resources: string[] = []): Observable<SolutionCreatorInfo> {
this.initLoadingState();
const startOrContinue$ = this.solutionId
@ -550,7 +551,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
return startOrContinue$.pipe(
switchMap(() =>
this.solutionCreator.chatSolution(this.solutionId, this.solutionStep(), msg, {ignoreLoading: true, ignoreErrors: true})
this.solutionCreator.chatSolution(this.solutionId, this.solutionStep(), msg, {ignoreLoading: true, ignoreErrors: true}, resources)
),
tap(solution => {
this.solutionInfo = solution;
@ -596,7 +597,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
}
}
private showErrorMessage(error: any): void {
showErrorMessage(error: any): void {
const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined;
const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message;
const showOnTop = this.creatorStep() === 'result' || this.isInitialEmpty();
@ -709,9 +710,11 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
this.sendMessage('<skip-interview/>').subscribe(() => {});
}
sendMsgFromUser(msg: string): void {
this.messages.update(list => [...list, {from: 'USER', content: msg}]);
this.sendMessage(msg).subscribe(() => {});
sendMsgFromUser(prompt: AiPromptMessage): void {
this.messages.update(list => [...list, prompt.resources.length
? {from: 'USER', content: prompt.message, resources: prompt.resources}
: {from: 'USER', content: prompt.message}]);
this.sendMessage(prompt.message, prompt.resources.map(resource => resource.id)).subscribe(() => {});
}
private initLoadingState(): void {

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

@ -138,8 +138,33 @@ export interface AiChatClientContext {
export interface SendChatMessageRequest {
message: string;
clientContext?: AiChatClientContext;
resources?: string[];
}
export interface AiResourceInfo {
id: string;
name: string;
mediaType: string;
size: number;
}
export interface AiResourceConfig {
maxSize: number;
maxPerMessage: number;
mediaTypes: string[];
extensions: string[];
}
export interface AiPromptMessage {
message: string;
resources: AiResourceInfo[];
}
export const AI_IMAGE_MEDIA_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp'];
export const isAiImageResource = (resource: Pick<AiResourceInfo, 'mediaType'>): boolean =>
AI_IMAGE_MEDIA_TYPES.includes(resource.mediaType);
export interface AiAssistantViewConfig {
listView: AiAssistantViewType;
listEntityId?: EntityId;

3
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, ToolExecutionResult } from '@shared/models/ai-chat.models';
import { ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models';
export interface SolutionInfo {
id: string;
@ -178,6 +178,7 @@ export interface GeneralChatMessage {
from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE';
content: string;
status?: 'INCOMPLETE';
resources?: AiResourceInfo[];
}
export interface ApprovalChatMessage {

6639
ui-ngx/src/assets/locale/locale.constant-el_GR.json

File diff suppressed because it is too large

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

@ -714,6 +714,32 @@
"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.",
"ask-the-assistant": "Ask the AI Assistant",
"send": "Send",
"new-line": "New line",
"focus-composer": "Focus the composer",
"shortcuts": "Shortcuts",
"add-files": "Add files",
"add-files-text": "PDFs, spreadsheets, images or text.",
"add-files-hint": "Up to {{count}}, {{size}} each. Or drop them here.",
"remove-file": "Remove {{name}}",
"attachment-failed": "Upload failed",
"attachment-load-failed": "The file couldn't be loaded",
"attachment-uploading": "Uploading · {{progress}} %",
"attachment-unsupported": "Not supported: a PDF, spreadsheet, image or text",
"attachment-larger-than": "Larger than {{size}}",
"attachment-svg-failed": "This SVG can't be converted to an image",
"attachment-over-limit": "More than {{count}} files",
"file-kind": {
"image": "Image",
"pdf": "PDF",
"table": "Table",
"document": "Document",
"slides": "Slides",
"json": "JSON",
"text": "Text",
"file": "File"
},
"rename-chat-title": "Rename this chat",
"export-chat": "Export chat",
"main-title": "Hello! I'm your AI Assistant"

10094
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

File diff suppressed because it is too large

6233
ui-ngx/src/assets/locale/locale.constant-no_NO.json

File diff suppressed because it is too large

5589
ui-ngx/src/assets/locale/locale.constant-sl_SI.json

File diff suppressed because it is too large

111
ui-ngx/src/styles.scss

@ -346,6 +346,117 @@ pre.tb-highlight {
}
}
.tb-popover.tb-ai-tip {
$tip-bg: #1f2a31;
.tb-popover-inner {
border-radius: 8px;
background-color: $tip-bg;
box-shadow: 0 6px 20px rgba(16, 24, 40, 0.22);
}
.tb-popover-inner-content {
padding: 0;
overflow: visible;
}
&[class*='tb-popover-placement-top'] > .tb-popover-content > .tb-popover-arrow {
border-right-color: $tip-bg;
border-bottom-color: $tip-bg;
box-shadow: none;
}
&[class*='tb-popover-placement-bottom'] > .tb-popover-content > .tb-popover-arrow {
border-top-color: $tip-bg;
border-left-color: $tip-bg;
box-shadow: none;
}
.tb-ai-tip-body {
box-sizing: border-box;
width: max-content;
max-width: min(248px, calc(100vw - 16px));
padding: 9px 12px 10px;
color: #d5dde2;
font: 400 12px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
letter-spacing: .1px;
b {
display: block;
margin: 0;
font-size: 13px;
line-height: 18px;
font-weight: 500;
color: #fff;
}
p {
margin: 0;
font: inherit;
letter-spacing: inherit;
}
p + p {
margin-top: 3px;
}
.tip-sub {
color: #9fadb7;
}
.tip-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
margin-bottom: 3px;
}
.tip-keyrow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
min-height: 22px;
}
.tip-caps {
display: inline-flex;
gap: 3px;
}
kbd {
min-width: 16px;
height: 17px;
box-sizing: border-box;
padding: 0 4px;
border: 0;
border-radius: 4px;
background: rgba(255, 255, 255, 0.14);
color: #fff;
font: 500 10.5px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
text-align: center;
}
&.tip-keys {
min-width: 208px;
.tip-head {
margin-bottom: 2px;
}
}
&.tip-mini {
padding: 5px 8px 6px;
.tip-keyrow {
gap: 10px;
min-height: 18px;
}
}
}
}
.tb-autocomplete {
.mat-mdc-option {
border-bottom: 1px solid #eee;

Loading…
Cancel
Save