diff --git a/application/src/main/java/org/thingsboard/server/controller/AiResourceController.java b/application/src/main/java/org/thingsboard/server/controller/AiResourceController.java new file mode 100644 index 0000000000..ed3339f64f --- /dev/null +++ b/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 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); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java index 0bd771ecee..3bc73f3428 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java +++ b/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 resources) {} + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/{solutionId}/create") public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java index 694e2a4c6b..f3b60383eb 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java +++ b/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); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java b/application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java new file mode 100644 index 0000000000..ece2210823 --- /dev/null +++ b/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) {} + +} diff --git a/application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java b/application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java new file mode 100644 index 0000000000..82788db693 --- /dev/null +++ b/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); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java index 514672a782..b0f7763131 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java +++ b/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 resources, SecurityUser user); JsonNode createSolution(UUID solutionId, SecurityUser user); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java index a93b1c6872..c110699cbd 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java +++ b/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 resources, SecurityUser user) { + String text = StringUtils.defaultString(message); + List 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 diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java index 3904f7b6e1..5d6b1c4846 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java +++ b/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; diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java index d587ff5e8d..92b16fde51 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java +++ b/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) diff --git a/application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java new file mode 100644 index 0000000000..5186939139 --- /dev/null +++ b/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); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java index e64ec390f0..4f48e5c6c2 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java +++ b/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 diff --git a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java index d67d93c204..723dc0131e 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java +++ b/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); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java index afeeca5223..a6f17b5582 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java +++ b/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"); } diff --git a/pom.xml b/pom.xml index 20438090bb..7b6c95ea3d 100755 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,7 @@ /var/log/${pkg.name} /usr/share/${pkg.name} control - 2.1.9-SNAPSHOT + 2.1.10-SNAPSHOT 4.4.0 3.5.15 -
@@ -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)">
} @else { @@ -86,22 +87,22 @@
} -
- @if (!messages().length && promptExamples().length) { -
- @for (example of promptExamples(); track example.message) { - - } -
- } - - -
+ @if (!messages().length && promptExamples().length) { +
+ @for (example of promptExamples(); track example.message) { + + } +
+ } + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss index 50be2f008d..0e5550eb38 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss +++ b/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; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts index c43a019591..fb7dadc790 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts +++ b/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 { + private sendMessage(prompt: AiPromptMessage): Observable { 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); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html new file mode 100644 index 0000000000..e81e8a2cf7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html @@ -0,0 +1,32 @@ + + +

{{ data.resource.name }}

+ + + +
+
+ @if (preview$ | async; as preview) { + @if (preview.url) { + + } @else { +
+ broken_image + {{ preview.error }} +
+ } + } @else { + + } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss new file mode 100644 index 0000000000..a99a8a99b3 --- /dev/null +++ b/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); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts new file mode 100644 index 0000000000..a456faf3b8 --- /dev/null +++ b/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 { + + readonly preview$: Observable; + + constructor(protected store: Store, + protected router: Router, + public dialogRef: MatDialogRef, + @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'); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts new file mode 100644 index 0000000000..ea7e35c04f --- /dev/null +++ b/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 = {'': 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 => 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 => 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 => { + 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 => { + 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; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html new file mode 100644 index 0000000000..db8c319e86 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html @@ -0,0 +1,30 @@ + +
+ @for (item of shown; track item.resource.id) { +
+ @if (item.image) { + @if (item.url$ | async; as url) { + + } @else { + image + } + } @else { +
{{ item.icon }}
+
+ {{ item.resource.name }} + {{ item.extension }}@if (item.extension) { · }{{ item.resource.size | fileSize }} +
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss new file mode 100644 index 0000000000..9da645eb8a --- /dev/null +++ b/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; + } + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts new file mode 100644 index 0000000000..86db1c6232 --- /dev/null +++ b/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; +} + +@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(); + + 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, { + 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) + }); + } + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html index 6aa2044848..7fd251f846 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/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') {
-
{{ msg.content }}
+ @if (msg.resources?.length) { + + } + @if (msg.content) { +
{{ msg.content }}
+ }
} @else {
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index ca71bcf0e0..c9b42e734e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/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%; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 914104bf65..7818491ccc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/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 = {}; @Input() autoApprove = false; @Output() approvalAction = new EventEmitter(); + @Output() resourceError = new EventEmitter(); waitApproval = false; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html index ad930b3c4b..082f2708b0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html @@ -4,27 +4,113 @@ SPDX-License-Identifier: BUSL-1.1 --> -
- - - - +
+ @if (attachEnabled()) { + + } +
+ @if (attachments().length) { +
+ @for (attachment of attachments(); track attachment.key) { + + @if (attachment.previewUrl && attachment.status !== 'error') { + + } @else { + {{ attachment.status === 'error' ? 'error_outline' : attachment.icon }} + } + + {{ attachment.name }} + {{ meta(attachment) }} + + @if (attachment.status === 'uploading') { + + } + + + } +
+ } +
+ + + + + +
+
+ @if (attachEnabled()) { + + } + + +
+
+ + +
+
+ {{ 'ai-assistant.send' | translate }} + Enter +
+
+
+ + +
+
{{ 'ai-assistant.add-files' | translate }}
+

{{ 'ai-assistant.add-files-text' | translate }}

+

{{ 'ai-assistant.add-files-hint' | translate: {count: maxPerMessage(), size: maxSize()} }}

+
+
+ + +
+
{{ 'ai-assistant.shortcuts' | translate }}
+
+ {{ 'ai-assistant.send' | translate }} + Enter +
+
+ {{ 'ai-assistant.new-line' | translate }} + ShiftEnter +
+
+ {{ 'ai-assistant.focus-composer' | translate }} + / +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss index 5eabeb4234..088c205465 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss +++ b/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; } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts index 57efd86bcf..5297f99045 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts +++ b/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); @Input() placeholder = ''; @Input() loading: boolean; - @Output() messageSent = new EventEmitter(); + @Input() docked = false; + + @Input() dropZone: HTMLElement; - @ViewChild('autosize') autosize!: CdkTextareaAutosize; + @Output() messageSent = new EventEmitter(); @ViewChild('textarea') textarea!: ElementRef; + @ViewChild('fileInput') fileInput!: ElementRef; + message = new FormControl(''); - 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([]); + + 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; + 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('.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 { + 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 { + 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): 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); + } + } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts new file mode 100644 index 0000000000..4c20bb7dfc --- /dev/null +++ b/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); + private renderer = inject(Renderer2); + + @Input('tbAiTip') template: TemplateRef; + + @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'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index 3d873e174f..d837940241 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/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 {} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts index 11a28f8a58..6051b13301 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts +++ b/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, + 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): void { const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); this.solutions.update(solutions => diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html index 09bd0a1763..9c901722c2 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html +++ b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html @@ -38,7 +38,7 @@ @switch (creatorStep()) { @case ('chat') {
-
@if (isInitialEmpty()) {
@@ -57,7 +57,8 @@ + [loadingLongTime]="loadingLongTime()" + (resourceError)="showErrorMessage($event)">
Loading
@@ -72,6 +73,7 @@ @if (isInitialEmpty()) { diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts index 0592b8270c..153de939fb 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts +++ b/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 { + private sendMessage(msg: string, resources: string[] = []): Observable { 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('').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 { diff --git a/ui-ngx/src/app/shared/models/ai-chat.models.ts b/ui-ngx/src/app/shared/models/ai-chat.models.ts index 988f370fec..4d4b19234e 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/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): boolean => + AI_IMAGE_MEDIA_TYPES.includes(resource.mediaType); + export interface AiAssistantViewConfig { listView: AiAssistantViewType; listEntityId?: EntityId; diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index f3a58718c8..5257dd27fb 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/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 { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 2450099fe5..e9967d3fde 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/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" diff --git a/ui-ngx/src/styles.scss b/ui-ngx/src/styles.scss index 7df150e010..42b01a636f 100644 --- a/ui-ngx/src/styles.scss +++ b/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;