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..f68fe5358b 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; @@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; 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.permission.Operation; 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.system.SystemSecurityService; +import java.util.List; import java.util.UUID; 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); } + @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 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/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..d52edb196a --- /dev/null +++ b/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); + } + +} 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..123cea7398 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 { @@ -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, List resources, SecurityUser user); + JsonNode createSolution(UUID solutionId, SecurityUser user); JsonNode updateData(UUID solutionId, String dataKey, JsonNode value, 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..c5c154c000 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 @@ -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.security.model.SecurityUser; +import java.util.List; import java.util.UUID; @Service @@ -48,8 +49,14 @@ public class DefaultAiSolutionService implements AiSolutionService { @Override 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 resources, SecurityUser user) { + List attached = resources == null || resources.isEmpty() ? null : resources; 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 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..567ad2b763 --- /dev/null +++ b/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); + } + +} diff --git a/ui-ngx/src/app/core/http/ai-resource.service.ts b/ui-ngx/src/app/core/http/ai-resource.service.ts new file mode 100644 index 0000000000..467fddd1b5 --- /dev/null +++ b/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; + + private readonly urls = new Map>(); + + constructor(private http: HttpClient) { + } + + getConfig(): Observable { + if (!this.config$) { + this.config$ = this.http.get('/api/ai/resources/config', defaultHttpOptions(true, true)).pipe( + catchError(() => { + this.config$ = null; + return of(null); + }), + shareReplay(1) + ); + } + return this.config$; + } + + upload(file: File): Observable { + const formData = new FormData(); + formData.append('file', file, file.name); + return this.http.post('/api/ai/resources', formData, { + ...defaultHttpUploadOptions(true, true), + observe: 'events', + reportProgress: true + }).pipe( + filter((event: HttpEvent) => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response), + map((event: HttpEvent): 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 { + this.urls.delete(resourceId); + return this.http.delete(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true)); + } + + rememberUrl(resourceId: string, url: string): void { + this.urls.set(resourceId, of(url)); + } + + getUrl(resourceId: string): Observable { + 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 { + 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) + ); + } + +} diff --git a/ui-ngx/src/app/core/http/solutions-creator.service.ts b/ui-ngx/src/app/core/http/solutions-creator.service.ts index bcf5655b7f..2cfc4b2bb2 100644 --- a/ui-ngx/src/app/core/http/solutions-creator.service.ts +++ b/ui-ngx/src/app/core/http/solutions-creator.service.ts @@ -39,8 +39,10 @@ export class SolutionsCreatorService { return this.http.post(`/api/ai/solution/${solutionId}/create`, '', defaultHttpOptionsFromConfig(config)); } - public chatSolution(solutionId: string, step: SolutionStep, msg: string, config?: RequestConfig): Observable { - return this.http.post(`/api/ai/solution/${solutionId}/${step}/chat`, msg, defaultHttpOptionsFromConfig(config)); + public chatSolution(solutionId: string, step: SolutionStep, msg: string, config?: RequestConfig, + resources: string[] = []): Observable { + return this.http.post(`/api/ai/solution/${solutionId}/${step}/messages`, + {message: msg, resources}, defaultHttpOptionsFromConfig(config)); } public updateSolutionData(solutionId: string, dataKey: SolutionDataKey, msg: SolutionDataValues, config?: RequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html index db6b0dad5c..1634a63779 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html @@ -4,7 +4,7 @@ SPDX-License-Identifier: BUSL-1.1 --> -
@@ -100,6 +100,8 @@ class="flex" [placeholder]="activePlaceholder()" [loading]="loading()" + toastTarget="aiAssistant" + [dropZone]="chatContainer" (messageSent)="sendMsgFromUser($event)">
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..c9fec14c1d 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 @@ -21,6 +21,7 @@ import { AiChatService } from '@core/http/ai-chat.service'; import { AiAssistantPromptExample, AiChatClientContext, + AiPromptMessage, ApprovalResult, ChatEvent, ChatInfo, @@ -235,10 +236,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 +354,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 +371,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})), 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..a58261f352 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html @@ -0,0 +1,27 @@ + + +

{{ data.item.name }}

+ + @if (data.item.resource) { + + } + +
+
+ @if (data.item.url$ | async; as url) { + + } @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..d872016784 --- /dev/null +++ b/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; + } + } +} 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..377cd59165 --- /dev/null +++ b/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, + private aiResourceService: AiResourceService) { + } + + download(): void { + if (this.data.item.resource) { + this.aiResourceService.download(this.data.item.resource).subscribe({error: () => {}}); + } + } + + close(): void { + this.dialogRef.close(); + } + +} 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..9af001b8e8 --- /dev/null +++ b/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; + 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 => 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 (!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}); +}; 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..f8967bbc3a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html @@ -0,0 +1,48 @@ + +
+ @for (item of shown; track item.key) { +
+ @if (item.image) { + @if (item.url$ | async; as url) { + + } @else { + image + } + } @else { +
{{ icon(item.mediaType, item.name) }}
+
+ {{ item.name }} + {{ extension(item.name) }}@if (extension(item.name)) { ยท }{{ item.size | fileSize }} +
+ } + @if (item.status === 'uploading') { +
+ +
+ } @else if (item.status === 'error') { +
error_outline
+ } + @if (removable) { + + } +
+ } +
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..0e7ca14fd2 --- /dev/null +++ b/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%); + } + } +} 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..30260b230f --- /dev/null +++ b/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(); + + 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, { + 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); + } + +} 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..348db6778f 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,12 @@ @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-prompt-input.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html index ad930b3c4b..04682fe714 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 @@ -5,26 +5,48 @@ -->
- + @if (attachments().length) { + + + } + - +
+ @if (attachEnabled()) { + + + } + + +
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..479a9779cf 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 @@ -4,27 +4,59 @@ width: 100%; .prompt-input { - border-radius: 12px; + border-radius: 16px; border: 1px solid rgba(0, 0, 0, 0.2); background-color: #fff; - position: relative; display: flex; + flex-direction: column; flex: 1; + transition: border-color 0.15s ease, box-shadow 0.15s ease; --mat-form-field-outlined-outline-width: 0px; --mat-form-field-outlined-focus-outline-width: 0px; - .send-button { - position: absolute; - right: 10px; - bottom: 10px; + &:focus-within { + border-color: rgba(0, 0, 0, 0.32); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); + } + + .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 { - .prompt-input { + .prompt-input .prompt-field { .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; } } } 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..422e510d36 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,46 @@ // 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, + inject, + Input, + OnChanges, + OnDestroy, + Output, + Renderer2, + signal, + SimpleChanges, + untracked, + ViewChild +} from '@angular/core'; import { FormControl } from '@angular/forms'; 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({ selector: 'tb-ai-prompt-input', @@ -10,20 +48,66 @@ 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 store = inject>(Store); + private translate = inject(TranslateService); + private sanitizer = inject(DomSanitizer); + private renderer = inject(Renderer2); + private host = inject>(ElementRef); + private fileSize = new FileSizePipe(); @Input() placeholder = ''; @Input() loading: boolean; - @Output() messageSent = new EventEmitter(); + @Input() toastTarget: string; + + @Input() dropZone: HTMLElement; + + @Output() messageSent = new EventEmitter(); @ViewChild('autosize') autosize!: CdkTextareaAutosize; @ViewChild('textarea') textarea!: ElementRef; + @ViewChild('fileInput') fileInput!: ElementRef; + message = new FormControl(''); + config = toSignal(this.aiResourceService.getConfig(), {initialValue: null as AiResourceConfig | null}); + + attachments = signal([]); + + 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 { const ke = event as KeyboardEvent; if (!ke.shiftKey) { @@ -33,17 +117,19 @@ export class AiPromptInputComponent { } 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.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 { @@ -57,4 +143,219 @@ export class AiPromptInputComponent { 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 { + 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): 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; + } + } + } 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..41c417bf77 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,8 @@ 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'; @NgModule({ declarations: [ @@ -23,7 +25,9 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry AiCreditsComponent, AiCreditsPopupComponent, AiLoadingModalComponent, - AiNoTelemetryModalComponent + AiNoTelemetryModalComponent, + AiAttachmentsComponent, + AiAttachmentPreviewDialogComponent ], imports: [ CommonModule, @@ -37,7 +41,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/solution-creator.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html index 09bd0a1763..e62faa3ee5 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()) {
@@ -72,6 +72,8 @@ @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..8dd5e75b91 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; @@ -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..1ee675c627 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,31 @@ 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 isAiImageResource = (resource: Pick): boolean => + ['image/png', 'image/jpeg', 'image/webp'].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 0a52b2ebf5..0a39075052 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,15 @@ "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.", + "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", "export-chat": "Export chat", "main-title": "Hello! I'm your AI Assistant"