From d582dea34264cffe5ed424cb2ecf498951329144 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 12:56:45 +0200 Subject: [PATCH] fix: address review of AI resources: TB AI owns the upload limit, one solution chat path, and composer, preview and tip fixes - Uploads take their size limit from TB AI's resource config and stream the base64 encoding from the file instead of loading its bytes - Solution chat has one service method that normalizes and validates the message; the old /chat endpoint is a deprecated adapter - Tips use tb-popover instead of a custom tooltip engine - Blob URLs are revoked on delete and eviction, images are kept in a bounded LRU cache, downloads are never cached, and at most 3 full-size fetches run at once - One icon map and one image type list for attachments; dead attachment code removed - The attachment preview extends DialogComponent and shows an error state; failed downloads show the error - An image counts as an uploading attachment while it is being resized; pasting text from Office keeps the text - A failed chat load clears the previous chat's messages and approvals --- .../controller/AiSolutionController.java | 12 +- .../ai/resource/DefaultAiResourceService.java | 19 +- .../ai/solution/AiSolutionService.java | 2 - .../ai/solution/DefaultAiSolutionService.java | 17 +- .../controller/AiResourceControllerTest.java | 17 +- .../DefaultAiSolutionServiceTest.java | 17 +- .../src/app/core/http/ai-resource.service.ts | 180 ++++++++++--- .../ai/ai-assistant-panel.component.html | 3 +- .../ai/ai-assistant-panel.component.ts | 6 +- ...i-attachment-preview-dialog.component.html | 25 +- ...i-attachment-preview-dialog.component.scss | 18 ++ .../ai-attachment-preview-dialog.component.ts | 57 ++++- .../components/ai/ai-attachment.models.ts | 37 +-- .../ai/ai-attachments.component.html | 30 +-- .../ai/ai-attachments.component.scss | 62 +---- .../components/ai/ai-attachments.component.ts | 66 +++-- .../ai/ai-chat-messages.component.html | 3 +- .../ai/ai-chat-messages.component.ts | 1 + .../ai/ai-prompt-input.component.html | 50 ++-- .../ai/ai-prompt-input.component.scss | 129 ---------- .../ai/ai-prompt-input.component.ts | 69 +++-- .../home/components/ai/ai-tip.directive.ts | 238 ++++++------------ .../solution-creator.component.html | 3 +- .../solution-creator.component.ts | 2 +- .../src/app/shared/models/ai-chat.models.ts | 4 +- .../assets/locale/locale.constant-en_US.json | 2 +- ui-ngx/src/styles.scss | 111 ++++++++ 27 files changed, 598 insertions(+), 582 deletions(-) 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 f68fe5358b..3bc73f3428 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java @@ -17,7 +17,6 @@ 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; @@ -64,14 +63,13 @@ public class AiSolutionController extends BaseController { return aiSolutionService.getSolutions(user); } + @Deprecated(forRemoval = true) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/{solutionId}/{step}/chat") public JsonNode chat(@PathVariable UUID solutionId, @PathVariable SolutionStep step, @RequestBody String message) throws ThingsboardException { - SecurityUser user = getCurrentUser(); - accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); - return aiSolutionService.chat(solutionId, step, message, user); + return sendMessage(solutionId, step, new SolutionChatMessage(message, null)); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @@ -81,11 +79,7 @@ public class AiSolutionController extends BaseController { @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); + return aiSolutionService.chat(solutionId, step, request.message(), request.resources(), user); } record SolutionChatMessage(String message, List resources) {} 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 index d52edb196a..82788db693 100644 --- 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 @@ -17,7 +17,11 @@ import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperations; import org.thingsboard.server.service.security.model.SecurityUser; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.UUID; @@ -26,8 +30,6 @@ import java.util.UUID; @RequiredArgsConstructor class DefaultAiResourceService implements AiResourceService { - static final long MAX_UPLOAD_BYTES = 7L * 1024 * 1024; - private final TbAiService tbAiService; private final TbAiOperations operations; @@ -42,12 +44,13 @@ class DefaultAiResourceService implements AiResourceService { if (file == null || file.isEmpty()) { throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } - if (file.getSize() > MAX_UPLOAD_BYTES) { + long maxSize = getConfig(user).path("maxSize").asLong(0); + if (maxSize > 0 && file.getSize() > maxSize) { throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); } String data; try { - data = Base64.getEncoder().encodeToString(file.getBytes()); + data = base64(file); } catch (IOException e) { throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL); } @@ -56,6 +59,14 @@ class DefaultAiResourceService implements AiResourceService { new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false); } + private static String base64(MultipartFile file) throws IOException { + var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4)); + try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) { + in.transferTo(encoder); + } + return encoded.toString(StandardCharsets.ISO_8859_1); + } + @Override public AiResourceContent download(UUID resourceId, SecurityUser user) { JsonNode content = tbAiService.process(tokenProvider -> operations.execute( 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 123cea7398..b0f7763131 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java @@ -17,8 +17,6 @@ public interface AiSolutionService { JsonNode getSolutions(SecurityUser user); - JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user); - JsonNode chat(UUID solutionId, SolutionStep step, String message, List resources, SecurityUser user); JsonNode createSolution(UUID solutionId, SecurityUser user); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java index c5c154c000..c110699cbd 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java @@ -4,8 +4,12 @@ package org.thingsboard.server.service.ai.solution; import com.fasterxml.jackson.databind.JsonNode; import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.thingsboard.ai.common.data.solution.SolutionStep; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.exception.ThingsboardRuntimeException; +import org.thingsboard.server.common.data.util.CollectionsUtil; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.SolutionChatRequest; @@ -47,16 +51,15 @@ public class DefaultAiSolutionService implements AiSolutionService { new TbAiOperation(ChannelProtocol.SOLUTION_LIST, null), user, tokenProvider), user, false); } - @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; + String text = StringUtils.defaultString(message); + List attached = CollectionsUtil.isEmpty(resources) ? null : resources; + if (StringUtils.isBlank(text) && attached == null) { + throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message, attached)), user, tokenProvider), user); + new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, 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 index 8f9c5c50c3..5186939139 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java @@ -28,6 +28,10 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -43,6 +47,7 @@ public class AiResourceControllerTest extends AbstractAiControllerTest { UUID resourceId = UUID.randomUUID(); ObjectNode info = resourceInfo(resourceId, "chart.png", "image/png", PNG.length); var request = new ResourceUploadRequest("chart.png", "image/png", Base64.getEncoder().encodeToString(PNG)); + givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(5 * 1024 * 1024))); givenOperation(ChannelProtocol.RESOURCE_UPLOAD, request, success(info)); // WHEN @@ -55,17 +60,23 @@ public class AiResourceControllerTest extends AbstractAiControllerTest { } @Test - public void shouldRejectAFileOverTheUploadLimit_withoutCallingTheAiService() throws Exception { + public void shouldRejectAFileOverTheAiServiceLimit_withoutUploadingIt() throws Exception { // GIVEN loginTenantAdmin(); + givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits(1024))); // WHEN - upload("huge.png", "image/png", new byte[7 * 1024 * 1024 + 1]) + upload("huge.png", "image/png", new byte[1025]) .andExpect(status().isBadRequest()) .andExpect(statusReason(equalTo("The file is too large: huge.png"))); // THEN - verifyNoAiCalls(); + verify(tbAiOperations, never()).execute(argThat(operation -> operation != null && ChannelProtocol.RESOURCE_UPLOAD.equals(operation.type())), + any(TbAiTurnContext.class)); + } + + static JsonNode limits(long maxSize) { + return JacksonUtil.newObjectNode().put("maxSize", maxSize).put("maxPerMessage", 5); } @Test diff --git a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java index d67d93c204..723dc0131e 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java @@ -22,6 +22,8 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperations; @@ -29,10 +31,12 @@ import org.thingsboard.server.service.ai.transport.TbAiTurnContext; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.List; import java.util.Objects; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; @@ -121,6 +125,17 @@ class DefaultAiSolutionServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldRejectWithoutCallingTheAiService_whenAMessageHasNeitherTextNorFiles() { + // WHEN + Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, null, List.of(), user)); + + // THEN + assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Message cannot be blank"); + assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS); + then(tbAiService).shouldHaveNoInteractions(); + } + @ParameterizedTest @EnumSource(SolutionStep.class) void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) { @@ -131,7 +146,7 @@ class DefaultAiSolutionServiceTest { given(tbAiService.process(any(), same(user))).willReturn(expectedResponse); // WHEN - JsonNode result = service.chat(solutionId, step, message, user); + JsonNode result = service.chat(solutionId, step, message, List.of(), user); // THEN assertThat(result).isSameAs(expectedResponse); diff --git a/ui-ngx/src/app/core/http/ai-resource.service.ts b/ui-ngx/src/app/core/http/ai-resource.service.ts index 467fddd1b5..daa465f5d8 100644 --- a/ui-ngx/src/app/core/http/ai-resource.service.ts +++ b/ui-ngx/src/app/core/http/ai-resource.service.ts @@ -1,16 +1,27 @@ // 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 { HttpClient, HttpErrorResponse, 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 { from, Observable, of, Subscription, throwError } from 'rxjs'; +import { catchError, filter, finalize, map, shareReplay, switchMap } from 'rxjs/operators'; import { AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; export type AiResourceUploadEvent = { type: 'progress'; progress: number } | { type: 'done'; resource: AiResourceInfo }; +interface CachedUrl { + url$: Observable; + url?: string; + size: number; + dropped?: boolean; +} + +const MAX_CONCURRENT_FETCHES = 3; +const MAX_CACHED_URLS = 40; +const MAX_CACHED_BYTES = 64 * 1024 * 1024; + @Injectable({ providedIn: 'root' }) @@ -18,7 +29,11 @@ export class AiResourceService { private config$: Observable; - private readonly urls = new Map>(); + private readonly urls = new Map(); + + private readonly waitingFetches: Array<() => void> = []; + + private activeFetches = 0; constructor(private http: HttpClient) { } @@ -55,42 +70,149 @@ export class AiResourceService { } delete(resourceId: string): Observable { - this.urls.delete(resourceId); + this.forget(resourceId); return this.http.delete(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true)); } - rememberUrl(resourceId: string, url: string): void { - this.urls.set(resourceId, of(url)); + rememberUrl(resourceId: string, url: string, size: number): void { + this.forget(resourceId); + this.urls.set(resourceId, {url$: of(url), url, size}); + this.evict(resourceId); } getUrl(resourceId: string): Observable { - 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$); + const cached = this.urls.get(resourceId); + if (cached) { + this.urls.delete(resourceId); + this.urls.set(resourceId, cached); + return cached.url$; } - return url$; + const entry: CachedUrl = {url$: null, size: 0}; + entry.url$ = this.fetch(resourceId).pipe( + map(blob => { + const url = URL.createObjectURL(blob); + if (entry.dropped) { + setTimeout(() => URL.revokeObjectURL(url)); + } else { + entry.url = url; + entry.size = blob.size; + this.evict(resourceId); + } + return url; + }), + catchError(error => { + if (this.urls.get(resourceId) === entry) { + this.urls.delete(resourceId); + } + throw error; + }), + shareReplay(1) + ); + this.urls.set(resourceId, entry); + return entry.url$; } download(resource: AiResourceInfo): Observable { - 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) + const cachedUrl = this.urls.get(resource.id)?.url; + if (cachedUrl) { + this.save(cachedUrl, resource.name); + return of(undefined); + } + return this.fetch(resource.id).pipe( + map(blob => { + const url = URL.createObjectURL(blob); + this.save(url, resource.name); + setTimeout(() => URL.revokeObjectURL(url)); + }) + ); + } + + private save(url: string, name: string): void { + const link = document.createElement('a'); + link.href = url; + link.download = name; + document.body.appendChild(link); + link.click(); + link.remove(); + } + + private fetch(resourceId: string): Observable { + const request$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe( + catchError(error => this.readErrorBody(error)) + ); + return new Observable(subscriber => { + let subscription: Subscription; + let finished = false; + const finish = () => { + if (!finished) { + finished = true; + this.activeFetches--; + this.waitingFetches.shift()?.(); + } + }; + const start = () => { + this.activeFetches++; + subscription = request$.pipe(finalize(finish)).subscribe(subscriber); + }; + if (this.activeFetches < MAX_CONCURRENT_FETCHES) { + start(); + } else { + this.waitingFetches.push(start); + } + return () => { + const index = this.waitingFetches.indexOf(start); + if (index >= 0) { + this.waitingFetches.splice(index, 1); + } + subscription?.unsubscribe(); + }; + }); + } + + private readErrorBody(error: any): Observable { + if (!(error instanceof HttpErrorResponse) || !(error.error instanceof Blob)) { + return throwError(() => error); + } + return from(error.error.text()).pipe( + catchError(() => of('')), + switchMap(text => throwError(() => new HttpErrorResponse({ + error: text || null, + headers: error.headers, + status: error.status, + statusText: error.statusText, + url: error.url ?? undefined + }))) ); } + private forget(resourceId: string): void { + const entry = this.urls.get(resourceId); + if (entry) { + this.urls.delete(resourceId); + this.release(entry); + } + } + + private release(entry: CachedUrl): void { + entry.dropped = true; + if (entry.url) { + URL.revokeObjectURL(entry.url); + } + } + + private evict(keep: string): void { + let bytes = 0; + this.urls.forEach(entry => bytes += entry.size); + for (const [resourceId, entry] of this.urls) { + if (this.urls.size <= MAX_CACHED_URLS && bytes <= MAX_CACHED_BYTES) { + break; + } + if (resourceId !== keep && entry.url) { + this.urls.delete(resourceId); + bytes -= entry.size; + this.release(entry); + } + } + } + } 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 ce957f8c4e..2e848e106f 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 @@ -69,7 +69,8 @@ [additionalStyles]="['.tb-markdown-view p, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5, .tb-markdown-view h6, .tb-markdown-view div.code-wrapper {padding-left: 0 !important;}' + '.tb-markdown-view ol {padding-inline-start: 30px;} .tb-markdown-view ul{padding-left: 28px;padding-right:0}' ]" - (approvalAction)="onApprovalAction($event)"> + (approvalAction)="onApprovalAction($event)" + (resourceError)="showErrorMessage($event)"> } @else { 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 9b68272d22..fb7dadc790 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts @@ -186,7 +186,9 @@ export class AiAssistantPanelComponent implements OnInit { this.loadChat$.pipe( switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( catchError(err => { - this.showErrorMessage(err); + this.messages.set([]); + this.completedExecutions.set({}); + setTimeout(() => this.showErrorMessage(err), 0); return EMPTY; }) )), @@ -535,7 +537,7 @@ export class AiAssistantPanelComponent implements OnInit { this.loading.set(false); } - private showErrorMessage(error: any): void { + showErrorMessage(error: any): void { const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; this.showErrorToast(message); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html index a58261f352..e81e8a2cf7 100644 --- 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 @@ -5,22 +5,27 @@ --> -

{{ data.item.name }}

+

{{ data.resource.name }}

- @if (data.item.resource) { - - } +
-
- @if (data.item.url$ | async; as url) { - +
+ @if (preview$ | async; as preview) { + @if (preview.url) { + + } @else { +
+ broken_image + {{ preview.error }} +
+ } } @else { } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss index d872016784..a99a8a99b3 100644 --- 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 @@ -28,5 +28,23 @@ object-fit: contain; border-radius: 8px; } + + .preview-error { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + padding: 32px 16px; + max-width: 360px; + color: rgba(0, 0, 0, 0.54); + text-align: center; + + mat-icon { + width: 40px; + height: 40px; + font-size: 40px; + color: rgba(0, 0, 0, 0.38); + } + } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts index 377cd59165..10f00bcdc0 100644 --- 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 @@ -2,11 +2,26 @@ // SPDX-License-Identifier: BUSL-1.1 import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { DomSanitizer } from '@angular/platform-browser'; +import { Observable, of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { AiAttachmentItem } from '@home/components/ai/ai-attachment.models'; +import { AiResourceInfo } from '@shared/models/ai-chat.models'; export interface AiAttachmentPreviewDialogData { - item: AiAttachmentItem; + resource: AiResourceInfo; +} + +interface AiAttachmentPreview { + url?: string; + error?: string; } @Component({ @@ -15,21 +30,45 @@ export interface AiAttachmentPreviewDialogData { styleUrls: ['./ai-attachment-preview-dialog.component.scss'], standalone: false }) -export class AiAttachmentPreviewDialogComponent { +export class AiAttachmentPreviewDialogComponent extends DialogComponent { + + readonly preview$: Observable; - constructor(@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData, - private dialogRef: MatDialogRef, - private aiResourceService: AiResourceService) { + constructor(protected store: Store, + protected router: Router, + public dialogRef: MatDialogRef, + @Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData, + private aiResourceService: AiResourceService, + private translate: TranslateService, + private sanitizer: DomSanitizer) { + super(store, router, dialogRef); + this.preview$ = this.aiResourceService.getUrl(data.resource.id).pipe( + map(url => ({url})), + catchError(error => of({error: this.errorMessage(error)})) + ); } download(): void { - if (this.data.item.resource) { - this.aiResourceService.download(this.data.item.resource).subscribe({error: () => {}}); - } + this.aiResourceService.download(this.data.resource).subscribe({ + error: error => this.store.dispatch(new ActionNotificationShow({ + message: this.errorMessage(error), + target: 'aiAttachmentPreview', + modern: true, + type: 'error', + verticalPosition: 'bottom', + horizontalPosition: 'center' + })) + }); } close(): void { this.dialogRef.close(); } + private errorMessage(error: any): 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-load-failed'); + } + } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts index 4b89b41a79..a96511ee69 100644 --- 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 @@ -1,39 +1,8 @@ // 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; -} +import { AI_IMAGE_MEDIA_TYPES } from '@shared/models/ai-chat.models'; 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 interface AiAttachmentKind { icon: string; @@ -81,7 +50,7 @@ export const isAiAttachmentAccepted = (file: File, extensions: string[]): boolea }; export const namePastedImage = (file: File): File => { - if (!RESIZABLE_IMAGE_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) { + if (!AI_IMAGE_MEDIA_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) { return file; } const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').substring(0, 15); @@ -107,7 +76,7 @@ const encode = (canvas: HTMLCanvasElement, type: string, quality?: number): Prom 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)) { + if (!AI_IMAGE_MEDIA_TYPES.includes(file.type)) { return file; } let image: HTMLImageElement; 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 index f8967bbc3a..db8c319e86 100644 --- 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 @@ -5,44 +5,26 @@ -->
- @for (item of shown; track item.key) { + @for (item of shown; track item.resource.id) {
@if (item.image) { @if (item.url$ | async; as url) { - + } @else { image } } @else { -
{{ icon(item.mediaType, item.name) }}
+
{{ item.icon }}
- {{ item.name }} - {{ extension(item.name) }}@if (extension(item.name)) { · }{{ item.size | fileSize }} + {{ item.resource.name }} + {{ item.extension }}@if (item.extension) { · }{{ item.resource.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 index 0e7ca14fd2..9da645eb8a 100644 --- 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 @@ -20,13 +20,10 @@ background: #fff; overflow: hidden; flex: none; + cursor: pointer; - &.clickable { - cursor: pointer; - - &:hover { - border-color: var(--tb-primary-500); - } + &:hover { + border-color: var(--tb-primary-500); } &.image { @@ -50,7 +47,7 @@ gap: 8px; height: 48px; max-width: 220px; - padding: 0 28px 0 8px; + padding: 0 12px 0 8px; .file-icon { display: flex; @@ -100,56 +97,5 @@ } } } - - &.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 index 30260b230f..86db1c6232 100644 --- 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 @@ -2,18 +2,24 @@ // SPDX-License-Identifier: BUSL-1.1 import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; +import { Observable } from 'rxjs'; +import { catchError } from 'rxjs/operators'; import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { - aiAttachmentExtension, - aiAttachmentIcon, - AiAttachmentItem -} from '@home/components/ai/ai-attachment.models'; +import { aiAttachmentExtension, aiAttachmentKind } from '@home/components/ai/ai-attachment.models'; import { AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData } from '@home/components/ai/ai-attachment-preview-dialog.component'; +interface AiAttachmentItem { + resource: AiResourceInfo; + image: boolean; + icon: string; + extension: string; + url$?: Observable; +} + @Component({ selector: 'tb-ai-attachments', templateUrl: './ai-attachments.component.html', @@ -24,55 +30,41 @@ export class AiAttachmentsComponent implements OnChanges { @Input() resources: AiResourceInfo[]; - @Input() items: AiAttachmentItem[]; - - @Input() removable = false; - - @Output() removed = new EventEmitter(); + @Output() resourceError = 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' - })); + if (changes.resources) { + this.shown = (this.resources ?? []).map(resource => { + const image = isAiImageResource(resource); + return { + resource, + image, + icon: aiAttachmentKind(resource.mediaType, resource.name).icon, + extension: aiAttachmentExtension(resource.name), + url$: image ? this.aiResourceService.getUrl(resource.id).pipe(catchError(() => [null])) : undefined + }; + }); } } open(item: AiAttachmentItem): void { - if (item.status === 'uploading' || item.status === 'error') { - return; - } - if (item.image && item.url$) { + if (item.image) { this.dialog.open(AiAttachmentPreviewDialogComponent, { panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], maxWidth: '92vw', - data: {item} + data: {resource: item.resource} + }); + } else { + this.aiResourceService.download(item.resource).subscribe({ + error: error => this.resourceError.emit(error) }); - } 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 348db6778f..7fd251f846 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html @@ -8,7 +8,8 @@ @if (msg.from === 'USER') {
@if (msg.resources?.length) { - + } @if (msg.content) {
{{ msg.content }}
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 914104bf65..7818491ccc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -19,6 +19,7 @@ export class AiChatMessagesComponent implements OnChanges { @Input() completedExecutions: Record = {}; @Input() autoApprove = false; @Output() approvalAction = new EventEmitter(); + @Output() resourceError = new EventEmitter(); waitApproval = false; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html index 61b4f6e799..082f2708b0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html @@ -52,8 +52,7 @@ [class.fly]="flying()" [disabled]="!canSend" [attr.aria-label]="'ai-assistant.send' | translate" - [tbAiTip]="sendTip" - tipClass="tip-mini" + tb-popover [tbAiTip]="sendTip" (click)="send()">
-
- {{ 'ai-assistant.send' | translate }} - Enter +
+
+ {{ 'ai-assistant.send' | translate }} + Enter +
-
{{ 'ai-assistant.add-files' | translate }}
-

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

-

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

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

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

+

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

+
-
{{ 'ai-assistant.shortcuts' | translate }}
-
- {{ 'ai-assistant.send' | translate }} - Enter -
-
- {{ 'ai-assistant.new-line' | translate }} - ShiftEnter -
-
- {{ 'ai-assistant.focus-composer' | translate }} - / +
+
{{ 'ai-assistant.shortcuts' | translate }}
+
+ {{ 'ai-assistant.send' | translate }} + Enter +
+
+ {{ 'ai-assistant.new-line' | translate }} + ShiftEnter +
+
+ {{ 'ai-assistant.focus-composer' | translate }} + / +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss index 30c40cbe36..088c205465 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss @@ -452,132 +452,3 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } } } - -::ng-deep .tb-ai-tip { - position: fixed; - left: 0; - top: 0; - z-index: 1100; - box-sizing: border-box; - width: max-content; - max-width: min(248px, calc(100vw - 16px)); - padding: 9px 12px 10px; - border-radius: 8px; - background: #1f2a31; - color: #d5dde2; - font: 400 12px/17px $font; - letter-spacing: .1px; - box-shadow: 0 6px 20px rgba(16, 24, 40, 0.22); - opacity: 0; - transform: translateY(4px); - pointer-events: none; - transition: opacity .12s ease, transform .16s cubic-bezier(.2, 0, 0, 1); - - &.below { - transform: translateY(-4px); - } - - &.on { - opacity: 1; - transform: none; - } - - &::after { - content: ''; - position: absolute; - left: var(--arrow-x, 50%); - top: 100%; - margin-left: -5px; - border: 5px solid transparent; - border-top-color: #1f2a31; - } - - &.below::after { - top: auto; - bottom: 100%; - border-top-color: transparent; - border-bottom-color: #1f2a31; - } - - b { - display: block; - margin: 0; - font-size: 13px; - line-height: 18px; - font-weight: 500; - color: #fff; - } - - p { - margin: 0; - font: inherit; - letter-spacing: inherit; - } - - p + p { - margin-top: 3px; - } - - .tip-sub { - color: #9fadb7; - } - - .tip-head { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 16px; - margin-bottom: 3px; - } - - .tip-keyrow { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - min-height: 22px; - } - - .tip-caps { - display: inline-flex; - gap: 3px; - } - - kbd { - min-width: 16px; - height: 17px; - box-sizing: border-box; - padding: 0 4px; - border: 0; - border-radius: 4px; - background: rgba(255, 255, 255, 0.14); - color: #fff; - font: 500 10.5px/17px $font; - text-align: center; - } - - &.tip-keys { - min-width: 208px; - - .tip-head { - margin-bottom: 2px; - } - } - - &.tip-mini { - min-width: 0; - padding: 5px 8px 6px; - - .tip-keyrow { - gap: 10px; - min-height: 18px; - } - } - - @media (prefers-reduced-motion: reduce) { - &, &.below { - transform: none; - transition: opacity .1s; - } - } -} 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 5fe50436e4..863d761d49 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 @@ -25,7 +25,7 @@ import { TranslateService } from '@ngx-translate/core'; import { DomSanitizer } from '@angular/platform-browser'; import { guid, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AI_IMAGE_MEDIA_TYPES, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; import { aiAttachmentKind, fitAiImage, @@ -48,7 +48,6 @@ interface PendingAttachment { upload?: Subscription; } -const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']; const FLY_DURATION = 520; @Component({ @@ -105,6 +104,7 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr private dragDepth = 0; private unlisten: Array<() => void> = []; private flyTimer: ReturnType; + private destroyed = false; get canSend(): boolean { const ready = this.attachments().some(attachment => attachment.status === 'ready'); @@ -125,6 +125,7 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } ngOnDestroy(): void { + this.destroyed = true; clearTimeout(this.flyTimer); this.stopListening(); this.clearAttachments(true); @@ -202,8 +203,9 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } onPaste(event: ClipboardEvent): void { - const files = Array.from(event.clipboardData?.files ?? []); - if (files.length && this.attachEnabled()) { + const clipboard = event.clipboardData; + const files = Array.from(clipboard?.files ?? []); + if (files.length && !clipboard.types.includes('text/plain') && this.attachEnabled()) { event.preventDefault(); this.addFiles(files.map(namePastedImage)); } @@ -224,27 +226,20 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr return `${this.translate.instant(attachment.kind)} · ${formatAiFileSize(attachment.size)}`; } - async addFiles(files: File[]): Promise { + addFiles(files: File[]): void { const config = this.config(); if (!config || !files.length) { return; } - for (const original of files) { + for (const file of files) { const accepted = this.attachments().filter(attachment => attachment.status !== 'error').length; if (accepted >= config.maxPerMessage) { - this.refuse(original, this.translate.instant('ai-assistant.attachment-over-limit', {count: config.maxPerMessage})); - continue; + this.refuse(file, this.translate.instant('ai-assistant.attachment-over-limit', {count: config.maxPerMessage})); + } else if (!isAiAttachmentAccepted(file, config.extensions)) { + this.refuse(file, this.translate.instant('ai-assistant.attachment-unsupported')); + } else { + this.prepare(file, config); } - if (!isAiAttachmentAccepted(original, config.extensions)) { - this.refuse(original, this.translate.instant('ai-assistant.attachment-unsupported')); - continue; - } - const file = await fitAiImage(original, config.maxSize); - if (file.size > config.maxSize) { - this.refuse(original, this.translate.instant('ai-assistant.attachment-larger-than', {size: formatAiFileSize(config.maxSize)})); - continue; - } - this.startUpload(file, config); } } @@ -262,29 +257,49 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr return {key: guid(), name: file.name, size: file.size, icon: kind.icon, kind: kind.label}; } - private startUpload(file: File, config: AiResourceConfig): void { - const previewUrl = IMAGE_TYPES.includes(file.type) ? URL.createObjectURL(file) : undefined; + private async prepare(original: File, config: AiResourceConfig): Promise { const attachment: PendingAttachment = { - ...this.describe(file, file.type || config.mediaTypes[0]), - previewUrl, + ...this.describe(original, original.type || config.mediaTypes[0]), status: 'uploading', progress: 0 }; this.attachments.update(list => [...list, attachment]); + let file: File; + try { + file = await fitAiImage(original, config.maxSize); + } catch { + file = original; + } + if (this.destroyed || !this.attachments().some(candidate => candidate.key === attachment.key)) { + return; + } + if (file.size > config.maxSize) { + this.patch(attachment.key, { + status: 'error', + reason: this.translate.instant('ai-assistant.attachment-larger-than', {size: formatAiFileSize(config.maxSize)}) + }); + return; + } + this.startUpload(attachment.key, file, config); + } + + private startUpload(key: string, file: File, config: AiResourceConfig): void { + const previewUrl = AI_IMAGE_MEDIA_TYPES.includes(file.type) ? URL.createObjectURL(file) : undefined; + this.patch(key, {...this.describe(file, file.type || config.mediaTypes[0]), key, previewUrl}); const upload = this.aiResourceService.upload(file).subscribe({ next: event => { if (event.type === 'progress') { - this.patch(attachment.key, {progress: event.progress}); + this.patch(key, {progress: event.progress}); } else { if (previewUrl) { - this.aiResourceService.rememberUrl(event.resource.id, previewUrl); + this.aiResourceService.rememberUrl(event.resource.id, previewUrl, file.size); } - this.patch(attachment.key, {status: 'ready', resource: event.resource, progress: 100}); + this.patch(key, {status: 'ready', resource: event.resource, progress: 100}); } }, - error: error => this.patch(attachment.key, {status: 'error', reason: this.errorMessage(error)}) + error: error => this.patch(key, {status: 'error', reason: this.errorMessage(error)}) }); - this.patch(attachment.key, {upload}); + this.patch(key, {upload}); } private patch(key: string, changes: Partial): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts index 906f1b19ea..4c20bb7dfc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts @@ -1,216 +1,118 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - Directive, - ElementRef, - EmbeddedViewRef, - HostListener, - inject, - Injector, - Input, - NgZone, - OnDestroy, - TemplateRef -} from '@angular/core'; - -const SHOW_DELAY = 350; -const HIDE_DELAY = 80; -const MARGIN = 8; -const GAP = 10; -const TIP_ID = 'tb-ai-tip'; - -// One floating tip for the composer's controls: it lives on the page, so a scrolling log or a panel's edge never clips it. -// A pointer opens it after a short pause and moving to the next control swaps it at once; keyboard focus opens it at once; -// blur, Esc, a scroll or a resize close it. It sits above its control, kept 8px inside the window, below when there is no room. -class AiTipHost { - - private element: HTMLElement; - private owner: AiTipDirective; - private view: EmbeddedViewRef; - private showTimer: ReturnType; - private hideTimer: ReturnType; - private frame = 0; - private listening = false; - - get open(): boolean { - return !!this.owner; - } - - isOwner(tip: AiTipDirective): boolean { - return this.owner === tip; - } - - scheduleShow(tip: AiTipDirective): void { - this.clearTimers(); - this.showTimer = setTimeout(() => this.show(tip), this.owner ? 0 : SHOW_DELAY); - } - - scheduleHide(tip: AiTipDirective): void { - clearTimeout(this.showTimer); - this.hideTimer = setTimeout(() => { - if (this.owner === tip) { - this.hide(); - } - }, HIDE_DELAY); - } - - show(tip: AiTipDirective): void { - this.clearTimers(); - this.listen(); - const element = this.ensure(); - if (this.owner && this.owner !== tip) { - this.owner.trigger.removeAttribute('aria-describedby'); - } - this.view?.destroy(); - this.view = tip.render(); - element.className = 'tb-ai-tip ' + (tip.tipClass || ''); - element.replaceChildren(...this.view.rootNodes); - this.owner = tip; - tip.trigger.setAttribute('aria-describedby', TIP_ID); - cancelAnimationFrame(this.frame); - this.place(); - element.classList.add('on'); - } +import { Directive, ElementRef, HostListener, inject, Input, OnDestroy, OnInit, Renderer2, TemplateRef } from '@angular/core'; +import { Subscription } from 'rxjs'; +import { TbPopoverDirective } from '@shared/components/popover.component'; - hide(): void { - clearTimeout(this.showTimer); - cancelAnimationFrame(this.frame); - if (!this.owner) { - return; - } - this.owner.trigger.removeAttribute('aria-describedby'); - this.owner = null; - this.element?.classList.remove('on'); - this.view?.destroy(); - this.view = null; - } - - private place(): void { - if (!this.owner) { - return; - } - const trigger = this.owner.trigger; - if (!trigger.isConnected) { - this.hide(); - return; - } - this.view?.detectChanges(); - const target = trigger.getBoundingClientRect(); - const tip = this.element.getBoundingClientRect(); - const center = target.left + target.width / 2; - const left = Math.round(Math.min(Math.max(MARGIN, center - tip.width / 2), innerWidth - tip.width - MARGIN)); - const below = target.top - tip.height - GAP < MARGIN; - const top = Math.round(below ? target.bottom + GAP : target.top - tip.height - GAP); - this.element.style.left = left + 'px'; - this.element.style.top = top + 'px'; - this.element.classList.toggle('below', below); - this.element.style.setProperty('--arrow-x', Math.round(Math.min(Math.max(12, center - left), tip.width - 12)) + 'px'); - this.frame = requestAnimationFrame(() => this.place()); - } - - private ensure(): HTMLElement { - if (!this.element) { - this.element = document.createElement('div'); - this.element.id = TIP_ID; - this.element.setAttribute('role', 'tooltip'); - document.body.appendChild(this.element); - } - return this.element; - } - - private listen(): void { - if (this.listening) { - return; - } - this.listening = true; - addEventListener('scroll', () => this.hide(), true); - addEventListener('resize', () => this.hide()); - document.addEventListener('keydown', (event) => { - if (event.key === 'Escape' && this.owner) { - this.hide(); - } - }); - } - - private clearTimers(): void { - clearTimeout(this.showTimer); - clearTimeout(this.hideTimer); - } -} +const SHOW_DELAY = 0.35; +const HIDE_DELAY = 0.08; +const TIP_ID = 'tb-ai-tip'; -const tipHost = new AiTipHost(); +const openTip: { current: AiTipDirective | null } = {current: null}; @Directive({ selector: '[tbAiTip]', standalone: false }) -export class AiTipDirective implements OnDestroy { +export class AiTipDirective implements OnInit, OnDestroy { + private popover = inject(TbPopoverDirective, {self: true}); private elementRef = inject>(ElementRef); - private injector = inject(Injector); - private zone = inject(NgZone); - - @Input('tbAiTip') template: TemplateRef; + private renderer = inject(Renderer2); - @Input() tipClass: string; + @Input('tbAiTip') template: TemplateRef; @Input() tipToggle = false; - get trigger(): HTMLElement { + private pointerType: string; + private visibleSubscription: Subscription; + private unlistenKeydown: () => void; + + private get trigger(): HTMLElement { return this.elementRef.nativeElement; } - render(): EmbeddedViewRef { - const view = this.template.createEmbeddedView(null, this.injector); - view.detectChanges(); - return view; + ngOnInit(): void { + this.popover.content = this.template; + this.popover.trigger = 'hover'; + this.popover.placement = ['top', 'topRight', 'topLeft', 'bottom', 'bottomRight', 'bottomLeft']; + this.popover.showCloseButton = false; + this.popover.mouseEnterDelay = SHOW_DELAY; + this.popover.mouseLeaveDelay = HIDE_DELAY; + this.popover.overlayClassName = 'tb-ai-tip'; + this.visibleSubscription = this.popover.visibleChange.subscribe(visible => visible ? this.onShown() : this.onHidden()); + } + + ngOnDestroy(): void { + this.visibleSubscription?.unsubscribe(); + this.onHidden(); } @HostListener('pointerenter', ['$event']) onPointerEnter(event: PointerEvent): void { - if (event.pointerType !== 'touch') { - this.zone.runOutsideAngular(() => tipHost.scheduleShow(this)); - } + this.pointerType = event.pointerType; + const other = openTip.current !== this ? openTip.current : null; + this.popover.mouseEnterDelay = other ? 0 : SHOW_DELAY; + other?.popover.hide(); } - @HostListener('pointerleave', ['$event']) - onPointerLeave(event: PointerEvent): void { - if (event.pointerType !== 'touch') { - tipHost.scheduleHide(this); + @HostListener('mouseenter', ['$event']) + onMouseEnter(event: MouseEvent): void { + if (this.pointerType === 'touch') { + event.stopImmediatePropagation(); } } @HostListener('focus') onFocus(): void { if (this.trigger.matches(':focus-visible')) { - this.zone.runOutsideAngular(() => tipHost.show(this)); + this.popover.show(); } } @HostListener('blur') onBlur(): void { - if (tipHost.isOwner(this)) { - tipHost.hide(); - } + this.popover.hide(); } @HostListener('click', ['$event']) onClick(event: MouseEvent): void { - if (!this.tipToggle) { - tipHost.hide(); + if (!this.tipToggle || this.popover.component?.visible) { + this.popover.hide(); return; } event.preventDefault(); - if (tipHost.isOwner(this)) { - tipHost.hide(); - } else { - this.zone.runOutsideAngular(() => tipHost.show(this)); + this.popover.show(); + } + + private onShown(): void { + if (openTip.current !== this) { + openTip.current?.popover.hide(); } + openTip.current = this; + this.unlistenKeydown?.(); + this.unlistenKeydown = this.renderer.listen('document', 'keydown', (event: KeyboardEvent) => { + if (event.key === 'Escape') { + this.popover.hide(); + } + }); + Promise.resolve().then(() => { + const pane = this.popover.component?.overlay?.overlayRef?.overlayElement; + const tip = pane?.querySelector('.tb-popover-inner'); + if (openTip.current === this && tip) { + this.renderer.setStyle(pane, 'pointer-events', 'none'); + tip.id = TIP_ID; + this.trigger.setAttribute('aria-describedby', TIP_ID); + } + }); } - ngOnDestroy(): void { - if (tipHost.isOwner(this)) { - tipHost.hide(); + private onHidden(): void { + if (openTip.current === this) { + openTip.current = null; } + this.unlistenKeydown?.(); + this.unlistenKeydown = null; + this.trigger.removeAttribute('aria-describedby'); } } diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html index 273961c214..9c901722c2 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html +++ b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html @@ -57,7 +57,8 @@ + [loadingLongTime]="loadingLongTime()" + (resourceError)="showErrorMessage($event)">
Loading
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 8dd5e75b91..153de939fb 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts @@ -597,7 +597,7 @@ export class SolutionCreatorComponent extends PageComponent implements OnInit, O } } - private showErrorMessage(error: any): void { + showErrorMessage(error: any): void { const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; const showOnTop = this.creatorStep() === 'result' || this.isInitialEmpty(); 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 1ee675c627..4d4b19234e 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -160,8 +160,10 @@ export interface AiPromptMessage { resources: AiResourceInfo[]; } +export const AI_IMAGE_MEDIA_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp']; + export const isAiImageResource = (resource: Pick): boolean => - ['image/png', 'image/jpeg', 'image/webp'].includes(resource.mediaType); + AI_IMAGE_MEDIA_TYPES.includes(resource.mediaType); export interface AiAssistantViewConfig { listView: AiAssistantViewType; 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 672aabeb2d..96c8ed3da1 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -723,8 +723,8 @@ "add-files-text": "PDFs, spreadsheets, images or text.", "add-files-hint": "Up to {{count}}, {{size}} each. Or drop them here.", "remove-file": "Remove {{name}}", - "remove-attachment": "Remove attachment", "attachment-failed": "Upload failed", + "attachment-load-failed": "The file couldn't be loaded", "attachment-uploading": "Uploading · {{progress}} %", "attachment-unsupported": "Not supported: a PDF, spreadsheet, image or text", "attachment-larger-than": "Larger than {{size}}", diff --git a/ui-ngx/src/styles.scss b/ui-ngx/src/styles.scss index 7df150e010..42b01a636f 100644 --- a/ui-ngx/src/styles.scss +++ b/ui-ngx/src/styles.scss @@ -346,6 +346,117 @@ pre.tb-highlight { } } +.tb-popover.tb-ai-tip { + $tip-bg: #1f2a31; + + .tb-popover-inner { + border-radius: 8px; + background-color: $tip-bg; + box-shadow: 0 6px 20px rgba(16, 24, 40, 0.22); + } + + .tb-popover-inner-content { + padding: 0; + overflow: visible; + } + + &[class*='tb-popover-placement-top'] > .tb-popover-content > .tb-popover-arrow { + border-right-color: $tip-bg; + border-bottom-color: $tip-bg; + box-shadow: none; + } + + &[class*='tb-popover-placement-bottom'] > .tb-popover-content > .tb-popover-arrow { + border-top-color: $tip-bg; + border-left-color: $tip-bg; + box-shadow: none; + } + + .tb-ai-tip-body { + box-sizing: border-box; + width: max-content; + max-width: min(248px, calc(100vw - 16px)); + padding: 9px 12px 10px; + color: #d5dde2; + font: 400 12px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; + letter-spacing: .1px; + + b { + display: block; + margin: 0; + font-size: 13px; + line-height: 18px; + font-weight: 500; + color: #fff; + } + + p { + margin: 0; + font: inherit; + letter-spacing: inherit; + } + + p + p { + margin-top: 3px; + } + + .tip-sub { + color: #9fadb7; + } + + .tip-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 16px; + margin-bottom: 3px; + } + + .tip-keyrow { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + min-height: 22px; + } + + .tip-caps { + display: inline-flex; + gap: 3px; + } + + kbd { + min-width: 16px; + height: 17px; + box-sizing: border-box; + padding: 0 4px; + border: 0; + border-radius: 4px; + background: rgba(255, 255, 255, 0.14); + color: #fff; + font: 500 10.5px/17px Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; + text-align: center; + } + + &.tip-keys { + min-width: 208px; + + .tip-head { + margin-bottom: 2px; + } + } + + &.tip-mini { + padding: 5px 8px 6px; + + .tip-keyrow { + gap: 10px; + min-height: 18px; + } + } + } +} + .tb-autocomplete { .mat-mdc-option { border-bottom: 1px solid #eee;