Browse Source

feat: AI resources: attach images, PDFs, text and Office files to AI Assistant and Solution Creator messages

- New /api/ai/resources endpoints (config, upload, download, delete) proxy file uploads to TB AI over the channel.
- Solution Creator messages go through a new JSON endpoint /api/ai/solution/{id}/{step}/messages carrying the attached
  resource ids; the plain-text chat endpoint stays unchanged.
- The chat composer gets a + button, drag and drop onto the chat, paste of screenshots, image downscaling before
  upload, previews with upload progress and remove, and a toolbar layout below the text; sent messages show image
  thumbnails with a preview dialog and file chips that download the file.
pull/16551/head
Igor Kulikov 1 month ago
parent
commit
1c36cbf21b
  1. 88
      application/src/main/java/org/thingsboard/server/controller/AiResourceController.java
  2. 19
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  3. 24
      application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java
  4. 73
      application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java
  5. 3
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  6. 9
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  7. 195
      application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java
  8. 96
      ui-ngx/src/app/core/http/ai-resource.service.ts
  9. 6
      ui-ngx/src/app/core/http/solutions-creator.service.ts
  10. 4
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html
  11. 16
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  12. 27
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html
  13. 32
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss
  14. 35
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts
  15. 112
      ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts
  16. 48
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html
  17. 155
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss
  18. 78
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts
  19. 7
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  20. 17
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  21. 46
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html
  22. 48
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss
  23. 321
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts
  24. 9
      ui-ngx/src/app/modules/home/components/ai/ai.module.ts
  25. 4
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html
  26. 15
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts
  27. 23
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  28. 3
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  29. 9
      ui-ngx/src/assets/locale/locale.constant-en_US.json

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

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

19
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 com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.permission.Resource;
@ -24,6 +26,7 @@ import org.thingsboard.server.service.ai.solution.AiSolutionService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER; import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER;
@ -71,6 +74,22 @@ public class AiSolutionController extends BaseController {
return aiSolutionService.chat(solutionId, step, message, user); return aiSolutionService.chat(solutionId, step, message, user);
} }
@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);
String message = request.message() != null ? request.message() : "";
if (message.isBlank() && (request.resources() == null || request.resources().isEmpty())) {
throw new ThingsboardException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return aiSolutionService.chat(solutionId, step, message, request.resources(), user);
}
record SolutionChatMessage(String message, List<UUID> resources) {}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/create") @PostMapping("/{solutionId}/create")
public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException { public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException {

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

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

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

@ -0,0 +1,73 @@
// 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.IOException;
import java.util.Base64;
import java.util.UUID;
@Service
@TbCoreComponent
@RequiredArgsConstructor
class DefaultAiResourceService implements AiResourceService {
static final long MAX_UPLOAD_BYTES = 7L * 1024 * 1024;
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);
}
if (file.getSize() > MAX_UPLOAD_BYTES) {
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
String data;
try {
data = Base64.getEncoder().encodeToString(file.getBytes());
} 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);
}
@Override
public AiResourceContent download(UUID resourceId, SecurityUser user) {
JsonNode content = tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(),
Base64.getDecoder().decode(content.path("data").asText()));
}
@Override
public void delete(UUID resourceId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
}
}

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

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

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

@ -18,6 +18,7 @@ import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext; import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID; import java.util.UUID;
@Service @Service
@ -48,8 +49,14 @@ public class DefaultAiSolutionService implements AiSolutionService {
@Override @Override
public JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user) { public JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user) {
return chat(solutionId, step, message, null, user);
}
@Override
public JsonNode chat(UUID solutionId, SolutionStep step, String message, List<UUID> resources, SecurityUser user) {
List<UUID> attached = resources == null || resources.isEmpty() ? null : resources;
return tbAiService.process(tokenProvider -> operations.execute( 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, message, attached)), user, tokenProvider), user);
} }
@Override @Override

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

@ -0,0 +1,195 @@
// 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.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_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 shouldRejectAFileOverTheUploadLimit_withoutCallingTheAiService() throws Exception {
// GIVEN
loginTenantAdmin();
// WHEN
upload("huge.png", "image/png", new byte[7 * 1024 * 1024 + 1])
.andExpect(status().isBadRequest())
.andExpect(statusReason(equalTo("The file is too large: huge.png")));
// THEN
verifyNoAiCalls();
}
@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 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);
}
}

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

@ -0,0 +1,96 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { defaultHttpOptions, defaultHttpUploadOptions } from '@core/http/http-utils';
import { Observable, of } from 'rxjs';
import { catchError, filter, map, shareReplay, tap } from 'rxjs/operators';
import { AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models';
export type AiResourceUploadEvent =
{ type: 'progress'; progress: number } |
{ type: 'done'; resource: AiResourceInfo };
@Injectable({
providedIn: 'root'
})
export class AiResourceService {
private config$: Observable<AiResourceConfig | null>;
private readonly urls = new Map<string, Observable<string>>();
constructor(private http: HttpClient) {
}
getConfig(): Observable<AiResourceConfig | null> {
if (!this.config$) {
this.config$ = this.http.get<AiResourceConfig>('/api/ai/resources/config', defaultHttpOptions(true, true)).pipe(
catchError(() => {
this.config$ = null;
return of(null);
}),
shareReplay(1)
);
}
return this.config$;
}
upload(file: File): Observable<AiResourceUploadEvent> {
const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post<AiResourceInfo>('/api/ai/resources', formData, {
...defaultHttpUploadOptions(true, true),
observe: 'events',
reportProgress: true
}).pipe(
filter((event: HttpEvent<AiResourceInfo>) => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response),
map((event: HttpEvent<AiResourceInfo>): AiResourceUploadEvent => {
if (event.type === HttpEventType.UploadProgress) {
return {type: 'progress', progress: event.total ? Math.round(100 * event.loaded / event.total) : 0};
}
return {type: 'done', resource: (event as any).body as AiResourceInfo};
})
);
}
delete(resourceId: string): Observable<void> {
this.urls.delete(resourceId);
return this.http.delete<void>(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true));
}
rememberUrl(resourceId: string, url: string): void {
this.urls.set(resourceId, of(url));
}
getUrl(resourceId: string): Observable<string> {
let url$ = this.urls.get(resourceId);
if (!url$) {
url$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe(
map(blob => URL.createObjectURL(blob)),
catchError(error => {
this.urls.delete(resourceId);
throw error;
}),
shareReplay(1)
);
this.urls.set(resourceId, url$);
}
return url$;
}
download(resource: AiResourceInfo): Observable<void> {
return this.getUrl(resource.id).pipe(
tap(url => {
const link = document.createElement('a');
link.href = url;
link.download = resource.name;
document.body.appendChild(link);
link.click();
link.remove();
}),
map(() => undefined)
);
}
}

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

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

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

@ -4,7 +4,7 @@
SPDX-License-Identifier: BUSL-1.1 SPDX-License-Identifier: BUSL-1.1
--> -->
<div class="ai-assistant-container relative" <div #chatContainer class="ai-assistant-container relative"
[class.fill]="panelService.detailsOpen() || !!panelService.config()?.fill" [class.fill]="panelService.detailsOpen() || !!panelService.config()?.fill"
[class.details-open]="panelService.detailsOpen()"> [class.details-open]="panelService.detailsOpen()">
<div class="ai-assistant-header"> <div class="ai-assistant-header">
@ -100,6 +100,8 @@
class="flex" class="flex"
[placeholder]="activePlaceholder()" [placeholder]="activePlaceholder()"
[loading]="loading()" [loading]="loading()"
toastTarget="aiAssistant"
[dropZone]="chatContainer"
(messageSent)="sendMsgFromUser($event)"> (messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input> </tb-ai-prompt-input>
</div> </div>

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

@ -21,6 +21,7 @@ import { AiChatService } from '@core/http/ai-chat.service';
import { import {
AiAssistantPromptExample, AiAssistantPromptExample,
AiChatClientContext, AiChatClientContext,
AiPromptMessage,
ApprovalResult, ApprovalResult,
ChatEvent, ChatEvent,
ChatInfo, ChatInfo,
@ -235,10 +236,12 @@ export class AiAssistantPanelComponent implements OnInit {
this.promptInput?.setValue(example.message); this.promptInput?.setValue(example.message);
} }
sendMsgFromUser(msg: string): void { sendMsgFromUser(prompt: AiPromptMessage): void {
const userMessage: ChatMessage = {from: 'USER', content: msg}; 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.messages.update(list => [...list, userMessage]);
this.sendMessage(msg).subscribe({ this.sendMessage(prompt).subscribe({
error: (err) => { error: (err) => {
if (this.isConnectionLost(err) && this.chatId()) { if (this.isConnectionLost(err) && this.chatId()) {
this.showErrorToast(this.translate.instant('ai-assistant.connection-lost')); this.showErrorToast(this.translate.instant('ai-assistant.connection-lost'));
@ -351,7 +354,7 @@ export class AiAssistantPanelComponent implements OnInit {
} }
} }
private sendMessage(msg: string): Observable<ChatEvent> { private sendMessage(prompt: AiPromptMessage): Observable<ChatEvent> {
this.initLoadingState(); this.initLoadingState();
this.sessionAffectedEntities = []; this.sessionAffectedEntities = [];
this.messageCancelled = false; this.messageCancelled = false;
@ -368,9 +371,12 @@ export class AiAssistantPanelComponent implements OnInit {
); );
const request: SendChatMessageRequest = { const request: SendChatMessageRequest = {
message: msg, message: prompt.message,
clientContext: this.resolveClientContextToSend() clientContext: this.resolveClientContextToSend()
}; };
if (prompt.resources.length) {
request.resources = prompt.resources.map(resource => resource.id);
}
return startOrContinue$.pipe( return startOrContinue$.pipe(
switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})),

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

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

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

@ -0,0 +1,32 @@
// 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;
}
}
}

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

@ -0,0 +1,35 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { AiResourceService } from '@core/http/ai-resource.service';
import { AiAttachmentItem } from '@home/components/ai/ai-attachment.models';
export interface AiAttachmentPreviewDialogData {
item: AiAttachmentItem;
}
@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 {
constructor(@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData,
private dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>,
private aiResourceService: AiResourceService) {
}
download(): void {
if (this.data.item.resource) {
this.aiResourceService.download(this.data.item.resource).subscribe({error: () => {}});
}
}
close(): void {
this.dialogRef.close();
}
}

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

@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Observable } from 'rxjs';
import { AiResourceInfo } from '@shared/models/ai-chat.models';
export interface AiAttachmentItem {
key: string;
name: string;
mediaType: string;
size: number;
image: boolean;
url$?: Observable<string>;
resource?: AiResourceInfo;
status?: 'uploading' | 'ready' | 'error';
progress?: number;
}
const MAX_IMAGE_SIDE = 2560;
const RESIZABLE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
export const aiAttachmentIcon = (mediaType: string, name: string): string => {
const extension = name.split('.').pop()?.toLowerCase();
if (mediaType === 'application/pdf' || extension === 'pdf') {
return 'picture_as_pdf';
}
if (extension === 'xlsx' || extension === 'csv') {
return 'table_chart';
}
if (extension === 'pptx') {
return 'slideshow';
}
if (['json', 'xml', 'yaml', 'yml', 'html', 'htm'].includes(extension)) {
return 'code';
}
return 'description';
};
export const aiAttachmentExtension = (name: string): string => {
const dot = name.lastIndexOf('.');
return dot > 0 ? name.substring(dot + 1).toUpperCase() : '';
};
export const isAiAttachmentAccepted = (file: File, extensions: string[]): boolean => {
const name = file.name.toLowerCase();
return extensions.some(extension => name.endsWith(extension.toLowerCase()));
};
export const namePastedImage = (file: File): File => {
if (!RESIZABLE_IMAGE_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) {
return file;
}
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').substring(0, 15);
const extension = file.type === 'image/jpeg' ? 'jpg' : file.type.split('/')[1];
return new File([file], `screenshot-${stamp}.${extension}`, {type: file.type, lastModified: file.lastModified});
};
const loadImage = (file: File): Promise<HTMLImageElement> => new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
URL.revokeObjectURL(url);
resolve(image);
};
image.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Image could not be decoded'));
};
image.src = url;
});
const encode = (canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> => new Promise((resolve, reject) =>
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Image could not be encoded')), type, quality));
export const fitAiImage = async (file: File, maxSize: number): Promise<File> => {
if (!RESIZABLE_IMAGE_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});
};

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

@ -0,0 +1,48 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="attachments">
@for (item of shown; track item.key) {
<div class="attachment"
[class.image]="item.image"
[class.file]="!item.image"
[class.uploading]="item.status === 'uploading'"
[class.failed]="item.status === 'error'"
[class.clickable]="item.status !== 'uploading' && item.status !== 'error'"
[matTooltip]="item.status === 'error' ? ('ai-assistant.attachment-failed' | translate) : item.name"
matTooltipPosition="above"
(click)="open(item)">
@if (item.image) {
@if (item.url$ | async; as url) {
<img [src]="url" [alt]="item.name">
} @else {
<mat-icon class="placeholder">image</mat-icon>
}
} @else {
<div class="file-icon"><mat-icon>{{ icon(item.mediaType, item.name) }}</mat-icon></div>
<div class="file-meta">
<span class="file-name">{{ item.name }}</span>
<span class="file-info">{{ extension(item.name) }}@if (extension(item.name)) { · }{{ item.size | fileSize }}</span>
</div>
}
@if (item.status === 'uploading') {
<div class="state">
<mat-progress-spinner diameter="24" strokeWidth="3"
[mode]="item.progress ? 'determinate' : 'indeterminate'"
[value]="item.progress"></mat-progress-spinner>
</div>
} @else if (item.status === 'error') {
<div class="state"><mat-icon class="error-icon">error_outline</mat-icon></div>
}
@if (removable) {
<button type="button" class="remove" [attr.aria-label]="'ai-assistant.remove-attachment' | translate"
(click)="remove($event, item)">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
</div>

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

@ -0,0 +1,155 @@
// 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;
&.clickable {
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 28px 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;
}
}
}
&.failed {
border-color: rgba(209, 39, 48, 0.6);
}
.state {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.7);
.error-icon {
color: rgb(209, 39, 48);
}
}
.remove {
position: absolute;
top: 4px;
right: 4px;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: #fff;
background: rgba(0, 0, 0, 0.6);
opacity: 0.9;
&:hover {
opacity: 1;
background: rgba(0, 0, 0, 0.8);
}
mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
}
&.file .remove {
top: 50%;
transform: translateY(-50%);
}
}
}

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

@ -0,0 +1,78 @@
// 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 { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models';
import { AiResourceService } from '@core/http/ai-resource.service';
import {
aiAttachmentExtension,
aiAttachmentIcon,
AiAttachmentItem
} from '@home/components/ai/ai-attachment.models';
import {
AiAttachmentPreviewDialogComponent,
AiAttachmentPreviewDialogData
} from '@home/components/ai/ai-attachment-preview-dialog.component';
@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[];
@Input() items: AiAttachmentItem[];
@Input() removable = false;
@Output() removed = new EventEmitter<AiAttachmentItem>();
shown: AiAttachmentItem[] = [];
readonly icon = aiAttachmentIcon;
readonly extension = aiAttachmentExtension;
constructor(private aiResourceService: AiResourceService,
private dialog: MatDialog) {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.items || changes.resources) {
this.shown = this.items ?? (this.resources ?? []).map(resource => ({
key: resource.id,
name: resource.name,
mediaType: resource.mediaType,
size: resource.size,
image: isAiImageResource(resource),
url$: isAiImageResource(resource) ? this.aiResourceService.getUrl(resource.id) : undefined,
resource,
status: 'ready'
}));
}
}
open(item: AiAttachmentItem): void {
if (item.status === 'uploading' || item.status === 'error') {
return;
}
if (item.image && item.url$) {
this.dialog.open<AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData>(AiAttachmentPreviewDialogComponent, {
panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'],
maxWidth: '92vw',
data: {item}
});
} else if (item.resource) {
this.aiResourceService.download(item.resource).subscribe({error: () => {}});
}
}
remove(event: Event, item: AiAttachmentItem): void {
event.stopPropagation();
this.removed.emit(item);
}
}

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

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

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

@ -15,7 +15,22 @@
.user { .user {
display: flex; 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 { .msg {
max-width: 80%; max-width: 80%;

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

@ -5,26 +5,48 @@
--> -->
<div class="prompt-input"> <div class="prompt-input">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="mr-10 flex-1"> @if (attachments().length) {
<tb-ai-attachments class="pending-attachments"
[items]="attachments()"
[removable]="true"
(removed)="removeAttachment($event)">
</tb-ai-attachments>
}
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="prompt-field">
<textarea <textarea
matInput matInput
#textarea #textarea
cdkTextareaAutosize cdkTextareaAutosize
rows="2" rows="1"
#autosize="cdkTextareaAutosize" #autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="2" cdkAutosizeMinRows="1"
cdkAutosizeMaxRows="6" cdkAutosizeMaxRows="8"
[placeholder]="placeholder" [placeholder]="placeholder"
[formControl]="message" [formControl]="message"
(paste)="onPaste($event)"
(keydown.enter)="onEnter($event)"> (keydown.enter)="onEnter($event)">
</textarea> </textarea>
</mat-form-field> </mat-form-field>
<button mat-icon-button <div class="prompt-toolbar">
type="button" @if (attachEnabled()) {
color="primary" <input #fileInput type="file" class="hidden" multiple [accept]="accept()" (change)="onFilesPicked($event)">
class="tb-mat-24 send-button !size-8" <button mat-icon-button
[disabled]="loading" type="button"
(click)="send()"> class="tb-mat-20 attach-button !size-8"
<mat-icon>send</mat-icon> [matTooltip]="'ai-assistant.attach-files' | translate"
</button> matTooltipPosition="above"
(click)="openFilePicker()">
<mat-icon>add</mat-icon>
</button>
}
<span class="flex-1"></span>
<button mat-icon-button
type="button"
color="primary"
class="tb-mat-20 send-button !size-8"
[disabled]="loading || uploading()"
(click)="send()">
<mat-icon>send</mat-icon>
</button>
</div>
</div> </div>

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

@ -4,27 +4,59 @@
width: 100%; width: 100%;
.prompt-input { .prompt-input {
border-radius: 12px; border-radius: 16px;
border: 1px solid rgba(0, 0, 0, 0.2); border: 1px solid rgba(0, 0, 0, 0.2);
background-color: #fff; background-color: #fff;
position: relative;
display: flex; display: flex;
flex-direction: column;
flex: 1; flex: 1;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
--mat-form-field-outlined-outline-width: 0px; --mat-form-field-outlined-outline-width: 0px;
--mat-form-field-outlined-focus-outline-width: 0px; --mat-form-field-outlined-focus-outline-width: 0px;
.send-button { &:focus-within {
position: absolute; border-color: rgba(0, 0, 0, 0.32);
right: 10px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
bottom: 10px; }
.pending-attachments {
padding: 12px 12px 0;
}
.prompt-field {
width: 100%;
}
.prompt-toolbar {
display: flex;
align-items: center;
gap: 4px;
padding: 0 8px 8px;
}
.attach-button {
color: rgba(0, 0, 0, 0.6);
border: 1px solid rgba(0, 0, 0, 0.16);
&:hover {
color: rgba(0, 0, 0, 0.87);
border-color: rgba(0, 0, 0, 0.32);
}
} }
} }
} }
:host::ng-deep { :host::ng-deep {
.prompt-input { .prompt-input .prompt-field {
.mdc-text-field--outlined { .mdc-text-field--outlined {
padding-right: 8px; padding-left: 16px;
padding-right: 16px;
}
.mat-mdc-form-field-infix {
padding-top: 14px;
padding-bottom: 6px;
min-height: 0;
} }
} }
} }

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

@ -1,8 +1,46 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core'; import {
AfterViewInit,
Component,
computed,
ElementRef,
EventEmitter,
inject,
Input,
OnChanges,
OnDestroy,
Output,
Renderer2,
signal,
SimpleChanges,
untracked,
ViewChild
} from '@angular/core';
import { FormControl } from '@angular/forms'; import { FormControl } from '@angular/forms';
import { CdkTextareaAutosize } from '@angular/cdk/text-field'; import { CdkTextareaAutosize } from '@angular/cdk/text-field';
import { toSignal } from '@angular/core/rxjs-interop';
import { of, Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { DomSanitizer } from '@angular/platform-browser';
import { AppState } from '@core/core.state';
import { ActionNotificationShow } from '@core/notification/notification.actions';
import { guid, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils';
import { AiResourceService } from '@core/http/ai-resource.service';
import { AiPromptMessage, AiResourceConfig } from '@shared/models/ai-chat.models';
import { FileSizePipe } from '@shared/pipe/file-size.pipe';
import {
AiAttachmentItem,
fitAiImage,
isAiAttachmentAccepted,
namePastedImage
} from '@home/components/ai/ai-attachment.models';
interface PendingAttachment extends AiAttachmentItem {
previewUrl?: string;
upload?: Subscription;
}
@Component({ @Component({
selector: 'tb-ai-prompt-input', selector: 'tb-ai-prompt-input',
@ -10,20 +48,66 @@ import { CdkTextareaAutosize } from '@angular/cdk/text-field';
styleUrls: ['./ai-prompt-input.component.scss'], styleUrls: ['./ai-prompt-input.component.scss'],
standalone: false standalone: false
}) })
export class AiPromptInputComponent { export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestroy {
private aiResourceService = inject(AiResourceService);
private store = inject<Store<AppState>>(Store);
private translate = inject(TranslateService);
private sanitizer = inject(DomSanitizer);
private renderer = inject(Renderer2);
private host = inject<ElementRef<HTMLElement>>(ElementRef);
private fileSize = new FileSizePipe();
@Input() placeholder = ''; @Input() placeholder = '';
@Input() loading: boolean; @Input() loading: boolean;
@Output() messageSent = new EventEmitter<string>(); @Input() toastTarget: string;
@Input() dropZone: HTMLElement;
@Output() messageSent = new EventEmitter<AiPromptMessage>();
@ViewChild('autosize') autosize!: CdkTextareaAutosize; @ViewChild('autosize') autosize!: CdkTextareaAutosize;
@ViewChild('textarea') textarea!: ElementRef<HTMLTextAreaElement>; @ViewChild('textarea') textarea!: ElementRef<HTMLTextAreaElement>;
@ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
message = new FormControl<string>(''); message = new FormControl<string>('');
config = toSignal(this.aiResourceService.getConfig(), {initialValue: null as AiResourceConfig | null});
attachments = signal<PendingAttachment[]>([]);
attachEnabled = computed(() => !!this.config());
accept = computed(() => this.config()?.extensions.join(',') ?? '');
uploading = computed(() => this.attachments().some(attachment => attachment.status === 'uploading'));
private dropTarget: HTMLElement;
private dropOverlay: HTMLElement;
private dragDepth = 0;
private unlisten: Array<() => void> = [];
ngOnChanges(changes: SimpleChanges): void {
if (changes.dropZone) {
this.listenForDrops(this.dropZone ?? this.host.nativeElement);
}
}
ngAfterViewInit(): void {
if (!this.dropTarget) {
this.listenForDrops(this.host.nativeElement);
}
}
ngOnDestroy(): void {
this.stopListening();
this.clearAttachments(true);
}
onEnter(event: Event): void { onEnter(event: Event): void {
const ke = event as KeyboardEvent; const ke = event as KeyboardEvent;
if (!ke.shiftKey) { if (!ke.shiftKey) {
@ -33,17 +117,19 @@ export class AiPromptInputComponent {
} }
send(): void { send(): void {
const msg = this.message.value?.trim(); const msg = this.message.value?.trim() ?? '';
if (msg && !this.loading) { const ready = this.attachments().filter(attachment => attachment.status === 'ready');
this.reset(); if (this.loading || this.uploading() || (!msg && !ready.length)) {
this.messageSent.emit(msg); return;
} }
this.clearText();
this.clearAttachments(false);
this.messageSent.emit({message: msg, resources: ready.map(attachment => attachment.resource)});
} }
reset(): void { reset(): void {
this.message.reset(''); this.clearText();
// Not autosize.reset(): it restores a height captured before the placeholder was known. this.clearAttachments(true);
this.autosize?.resizeToFitContent(true);
} }
focus(): void { focus(): void {
@ -57,4 +143,219 @@ export class AiPromptInputComponent {
this.autosize?.resizeToFitContent(true); this.autosize?.resizeToFitContent(true);
}); });
} }
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 files = Array.from(event.clipboardData?.files ?? []);
if (files.length && this.attachEnabled()) {
event.preventDefault();
this.addFiles(files.map(namePastedImage));
}
}
removeAttachment(item: AiAttachmentItem): void {
const attachment = this.attachments().find(candidate => candidate.key === item.key);
if (!attachment) {
return;
}
this.discard(attachment);
this.attachments.update(list => list.filter(candidate => candidate !== attachment));
}
async addFiles(files: File[]): Promise<void> {
const config = this.config();
if (!config || !files.length) {
return;
}
for (const original of files) {
if (this.attachments().length >= config.maxPerMessage) {
this.showError(this.translate.instant('ai-assistant.attachments-limit', {count: config.maxPerMessage}));
return;
}
if (!isAiAttachmentAccepted(original, config.extensions)) {
this.showError(this.translate.instant('ai-assistant.attachment-not-supported', {name: original.name}));
continue;
}
const file = await fitAiImage(original, config.maxSize);
if (file.size > config.maxSize) {
this.showError(this.translate.instant('ai-assistant.attachment-too-large',
{name: original.name, size: this.fileSize.transform(config.maxSize)}));
continue;
}
this.startUpload(file, config);
}
}
private startUpload(file: File, config: AiResourceConfig): void {
const image = ['image/png', 'image/jpeg', 'image/webp'].includes(file.type);
const previewUrl = image ? URL.createObjectURL(file) : undefined;
const attachment: PendingAttachment = {
key: guid(),
name: file.name,
mediaType: file.type || config.mediaTypes[0],
size: file.size,
image,
previewUrl,
url$: previewUrl ? of(previewUrl) : undefined,
status: 'uploading',
progress: 0
};
this.attachments.update(list => [...list, attachment]);
const upload = this.aiResourceService.upload(file).subscribe({
next: event => {
if (event.type === 'progress') {
this.patch(attachment.key, {progress: event.progress});
} else {
if (previewUrl) {
this.aiResourceService.rememberUrl(event.resource.id, previewUrl);
}
this.patch(attachment.key, {status: 'ready', resource: event.resource, progress: 100});
}
},
error: error => {
this.patch(attachment.key, {status: 'error'});
this.showError(this.errorMessage(error, file.name));
}
});
this.patch(attachment.key, {upload});
}
private patch(key: string, changes: Partial<PendingAttachment>): void {
this.attachments.update(list => list.map(attachment => attachment.key === key ? {...attachment, ...changes} : attachment));
}
private clearText(): void {
this.message.reset('');
// Not autosize.reset(): it restores a height captured before the placeholder was known.
this.autosize?.resizeToFitContent(true);
}
private clearAttachments(discard: boolean): void {
const attachments = untracked(() => this.attachments());
if (!attachments.length) {
return;
}
if (discard) {
attachments.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: any, name: string): string {
const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined;
const message = error ? parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message : null;
return message || this.translate.instant('ai-assistant.attachment-upload-failed', {name});
}
private showError(message: string): void {
this.store.dispatch(new ActionNotificationShow({
message,
target: this.toastTarget,
modern: true,
type: 'error',
verticalPosition: 'bottom',
horizontalPosition: 'center'
}));
}
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.showDropOverlay();
}
}),
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.hideDropOverlay();
}
}),
this.renderer.listen(target, 'drop', (event: DragEvent) => {
if (!hasFiles(event) || !this.attachEnabled()) {
return;
}
event.preventDefault();
this.dragDepth = 0;
this.hideDropOverlay();
this.addFiles(Array.from(event.dataTransfer.files ?? []));
})
];
}
private stopListening(): void {
this.unlisten.forEach(unlisten => unlisten());
this.unlisten = [];
this.dragDepth = 0;
this.hideDropOverlay();
}
private showDropOverlay(): void {
if (this.dropOverlay || !this.dropTarget) {
return;
}
const overlay: HTMLElement = this.renderer.createElement('div');
overlay.className = 'tb-ai-drop-overlay';
Object.assign(overlay.style, {
position: 'absolute', inset: '8px', zIndex: '20', display: 'flex', flexDirection: 'column', gap: '8px',
alignItems: 'center', justifyContent: 'center', borderRadius: '12px', pointerEvents: 'none',
border: '2px dashed var(--tb-primary-500)', background: 'rgba(255, 255, 255, 0.92)',
color: 'var(--tb-primary-500)', fontSize: '16px', fontWeight: '500', textAlign: 'center', padding: '16px'
});
const icon: HTMLElement = this.renderer.createElement('span');
icon.className = 'material-icons';
icon.style.fontSize = '40px';
icon.textContent = 'upload_file';
const title: HTMLElement = this.renderer.createElement('span');
title.textContent = this.translate.instant('ai-assistant.drop-files');
const hint: HTMLElement = this.renderer.createElement('span');
Object.assign(hint.style, {fontSize: '13px', fontWeight: '400', color: 'rgba(0, 0, 0, 0.54)'});
hint.textContent = this.translate.instant('ai-assistant.attachments-hint',
{size: this.fileSize.transform(this.config()?.maxSize ?? 0)});
overlay.append(icon, title, hint);
if (getComputedStyle(this.dropTarget).position === 'static') {
this.renderer.setStyle(this.dropTarget, 'position', 'relative');
}
this.renderer.appendChild(this.dropTarget, overlay);
this.dropOverlay = overlay;
}
private hideDropOverlay(): void {
if (this.dropOverlay) {
this.dropOverlay.remove();
this.dropOverlay = null;
}
}
} }

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

@ -12,6 +12,8 @@ import { AiCreditsComponent } from '@home/components/ai/ai-credits.component';
import { AiCreditsPopupComponent } from '@home/components/ai/ai-credits-popup.component'; import { AiCreditsPopupComponent } from '@home/components/ai/ai-credits-popup.component';
import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component';
import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-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';
@NgModule({ @NgModule({
declarations: [ declarations: [
@ -23,7 +25,9 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry
AiCreditsComponent, AiCreditsComponent,
AiCreditsPopupComponent, AiCreditsPopupComponent,
AiLoadingModalComponent, AiLoadingModalComponent,
AiNoTelemetryModalComponent AiNoTelemetryModalComponent,
AiAttachmentsComponent,
AiAttachmentPreviewDialogComponent
], ],
imports: [ imports: [
CommonModule, CommonModule,
@ -37,7 +41,8 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry
AiRenameDialogComponent, AiRenameDialogComponent,
AiCreditsComponent, AiCreditsComponent,
AiLoadingModalComponent, AiLoadingModalComponent,
AiNoTelemetryModalComponent AiNoTelemetryModalComponent,
AiAttachmentsComponent
] ]
}) })
export class AiModule {} export class AiModule {}

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

@ -38,7 +38,7 @@
@switch (creatorStep()) { @switch (creatorStep()) {
@case ('chat') { @case ('chat') {
<div class="chat-container flex w-full flex-auto rounded-lg"> <div class="chat-container flex w-full flex-auto rounded-lg">
<div class="chat relative flex size-full flex-col items-center justify-end gap-3" <div #chatArea class="chat relative flex size-full flex-col items-center justify-end gap-3"
[class.background]="isInitialEmpty()"> [class.background]="isInitialEmpty()">
@if (isInitialEmpty()) { @if (isInitialEmpty()) {
<div class="welcome-content"> <div class="welcome-content">
@ -72,6 +72,8 @@
<tb-ai-prompt-input <tb-ai-prompt-input
[placeholder]="activePlaceholder() | translate" [placeholder]="activePlaceholder() | translate"
[loading]="loading()" [loading]="loading()"
toastTarget="solution-creator-chat"
[dropZone]="chatArea"
(messageSent)="sendMsgFromUser($event)"> (messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input> </tb-ai-prompt-input>
@if (isInitialEmpty()) { @if (isInitialEmpty()) {

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

@ -16,6 +16,7 @@ import {
SolutionStepStatus SolutionStepStatus
} from '@shared/models/solution-creator.models'; } from '@shared/models/solution-creator.models';
import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; 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 { SolutionsCreatorService } from '@core/http/solutions-creator.service';
import { import {
catchError, catchError,
@ -507,7 +508,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
startCreateSolution(key: string) { startCreateSolution(key: string) {
const example = this.solutionExamples.find(ex => ex.key === key); const example = this.solutionExamples.find(ex => ex.key === key);
if (example) { 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(() => {}); }).afterClosed().subscribe(() => {});
} }
private sendMessage(msg: string): Observable<SolutionCreatorInfo> { private sendMessage(msg: string, resources: string[] = []): Observable<SolutionCreatorInfo> {
this.initLoadingState(); this.initLoadingState();
const startOrContinue$ = this.solutionId const startOrContinue$ = this.solutionId
@ -550,7 +551,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
return startOrContinue$.pipe( return startOrContinue$.pipe(
switchMap(() => 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 => { tap(solution => {
this.solutionInfo = solution; this.solutionInfo = solution;
@ -709,9 +710,11 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O
this.sendMessage('<skip-interview/>').subscribe(() => {}); this.sendMessage('<skip-interview/>').subscribe(() => {});
} }
sendMsgFromUser(msg: string): void { sendMsgFromUser(prompt: AiPromptMessage): void {
this.messages.update(list => [...list, {from: 'USER', content: msg}]); this.messages.update(list => [...list, prompt.resources.length
this.sendMessage(msg).subscribe(() => {}); ? {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 { private initLoadingState(): void {

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

@ -138,8 +138,31 @@ export interface AiChatClientContext {
export interface SendChatMessageRequest { export interface SendChatMessageRequest {
message: string; message: string;
clientContext?: AiChatClientContext; 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 isAiImageResource = (resource: Pick<AiResourceInfo, 'mediaType'>): boolean =>
['image/png', 'image/jpeg', 'image/webp'].includes(resource.mediaType);
export interface AiAssistantViewConfig { export interface AiAssistantViewConfig {
listView: AiAssistantViewType; listView: AiAssistantViewType;
listEntityId?: EntityId; listEntityId?: EntityId;

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

@ -7,7 +7,7 @@ import { EntityId } from '@shared/models/id/entity-id';
import { BaseData } from '@shared/models/base-data'; import { BaseData } from '@shared/models/base-data';
import { CalculatedFieldType } from '@shared/models/calculated-field.models'; import { CalculatedFieldType } from '@shared/models/calculated-field.models';
import { AlarmSeverity } from '@shared/models/alarm.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 { export interface SolutionInfo {
id: string; id: string;
@ -178,6 +178,7 @@ export interface GeneralChatMessage {
from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE'; from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE';
content: string; content: string;
status?: 'INCOMPLETE'; status?: 'INCOMPLETE';
resources?: AiResourceInfo[];
} }
export interface ApprovalChatMessage { export interface ApprovalChatMessage {

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

@ -714,6 +714,15 @@
"thinking": "Thinking...", "thinking": "Thinking...",
"connection-lost": "Connection to the AI Assistant was lost. Reconnecting...", "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.", "reconnect-failed": "Couldn't reconnect to the AI Assistant. Reopen the chat to see its reply.",
"attach-files": "Attach files",
"drop-files": "Drop files to attach",
"attachments-hint": "Images, PDF, text and Office files up to {{size}} each",
"remove-attachment": "Remove attachment",
"attachment-failed": "Upload failed",
"attachment-upload-failed": "Failed to upload {{name}}",
"attachment-not-supported": "{{name}} can't be attached: use images (PNG, JPEG, WebP), PDF, text files or Word, Excel and PowerPoint documents",
"attachment-too-large": "{{name}} is larger than {{size}}",
"attachments-limit": "A message can carry at most {{count}} files",
"rename-chat-title": "Rename this chat", "rename-chat-title": "Rename this chat",
"export-chat": "Export chat", "export-chat": "Export chat",
"main-title": "Hello! I'm your AI Assistant" "main-title": "Hello! I'm your AI Assistant"

Loading…
Cancel
Save