Browse Source

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
pull/16551/head
Igor Kulikov 4 weeks ago
parent
commit
d582dea342
  1. 12
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  2. 19
      application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java
  3. 2
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  4. 17
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  5. 17
      application/src/test/java/org/thingsboard/server/controller/AiResourceControllerTest.java
  6. 17
      application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
  7. 180
      ui-ngx/src/app/core/http/ai-resource.service.ts
  8. 3
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html
  9. 6
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  10. 25
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html
  11. 18
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.scss
  12. 57
      ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.ts
  13. 37
      ui-ngx/src/app/modules/home/components/ai/ai-attachment.models.ts
  14. 30
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.html
  15. 62
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss
  16. 66
      ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts
  17. 3
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  18. 1
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  19. 50
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html
  20. 129
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss
  21. 69
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts
  22. 238
      ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts
  23. 3
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.html
  24. 2
      ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.component.ts
  25. 4
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  26. 2
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  27. 111
      ui-ngx/src/styles.scss

12
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<UUID> resources) {}

19
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(

2
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<UUID> resources, SecurityUser user);
JsonNode createSolution(UUID solutionId, SecurityUser user);

17
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<UUID> resources, SecurityUser user) {
List<UUID> attached = resources == null || resources.isEmpty() ? null : resources;
String text = StringUtils.defaultString(message);
List<UUID> attached = CollectionsUtil.isEmpty(resources) ? null : resources;
if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message, attached)), user, tokenProvider), user);
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
}
@Override

17
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

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

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

180
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<string>;
url?: string;
size: number;
dropped?: boolean;
}
const MAX_CONCURRENT_FETCHES = 3;
const MAX_CACHED_URLS = 40;
const MAX_CACHED_BYTES = 64 * 1024 * 1024;
@Injectable({
providedIn: 'root'
})
@ -18,7 +29,11 @@ export class AiResourceService {
private config$: Observable<AiResourceConfig | null>;
private readonly urls = new Map<string, Observable<string>>();
private readonly urls = new Map<string, CachedUrl>();
private readonly waitingFetches: Array<() => void> = [];
private activeFetches = 0;
constructor(private http: HttpClient) {
}
@ -55,42 +70,149 @@ export class AiResourceService {
}
delete(resourceId: string): Observable<void> {
this.urls.delete(resourceId);
this.forget(resourceId);
return this.http.delete<void>(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true));
}
rememberUrl(resourceId: string, url: string): void {
this.urls.set(resourceId, of(url));
rememberUrl(resourceId: string, url: string, size: number): void {
this.forget(resourceId);
this.urls.set(resourceId, {url$: of(url), url, size});
this.evict(resourceId);
}
getUrl(resourceId: string): Observable<string> {
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<void> {
return this.getUrl(resource.id).pipe(
tap(url => {
const link = document.createElement('a');
link.href = url;
link.download = resource.name;
document.body.appendChild(link);
link.click();
link.remove();
}),
map(() => undefined)
const cachedUrl = this.urls.get(resource.id)?.url;
if (cachedUrl) {
this.save(cachedUrl, resource.name);
return of(undefined);
}
return this.fetch(resource.id).pipe(
map(blob => {
const url = URL.createObjectURL(blob);
this.save(url, resource.name);
setTimeout(() => URL.revokeObjectURL(url));
})
);
}
private save(url: string, name: string): void {
const link = document.createElement('a');
link.href = url;
link.download = name;
document.body.appendChild(link);
link.click();
link.remove();
}
private fetch(resourceId: string): Observable<Blob> {
const request$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe(
catchError(error => this.readErrorBody(error))
);
return new Observable<Blob>(subscriber => {
let subscription: Subscription;
let finished = false;
const finish = () => {
if (!finished) {
finished = true;
this.activeFetches--;
this.waitingFetches.shift()?.();
}
};
const start = () => {
this.activeFetches++;
subscription = request$.pipe(finalize(finish)).subscribe(subscriber);
};
if (this.activeFetches < MAX_CONCURRENT_FETCHES) {
start();
} else {
this.waitingFetches.push(start);
}
return () => {
const index = this.waitingFetches.indexOf(start);
if (index >= 0) {
this.waitingFetches.splice(index, 1);
}
subscription?.unsubscribe();
};
});
}
private readErrorBody(error: any): Observable<never> {
if (!(error instanceof HttpErrorResponse) || !(error.error instanceof Blob)) {
return throwError(() => error);
}
return from(error.error.text()).pipe(
catchError(() => of('')),
switchMap(text => throwError(() => new HttpErrorResponse({
error: text || null,
headers: error.headers,
status: error.status,
statusText: error.statusText,
url: error.url ?? undefined
})))
);
}
private forget(resourceId: string): void {
const entry = this.urls.get(resourceId);
if (entry) {
this.urls.delete(resourceId);
this.release(entry);
}
}
private release(entry: CachedUrl): void {
entry.dropped = true;
if (entry.url) {
URL.revokeObjectURL(entry.url);
}
}
private evict(keep: string): void {
let bytes = 0;
this.urls.forEach(entry => bytes += entry.size);
for (const [resourceId, entry] of this.urls) {
if (this.urls.size <= MAX_CACHED_URLS && bytes <= MAX_CACHED_BYTES) {
break;
}
if (resourceId !== keep && entry.url) {
this.urls.delete(resourceId);
bytes -= entry.size;
this.release(entry);
}
}
}
}

3
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)">
</tb-ai-chat-messages>
</div>
} @else {

6
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);

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

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

18
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);
}
}
}
}

57
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<AiAttachmentPreviewDialogComponent> {
readonly preview$: Observable<AiAttachmentPreview>;
constructor(@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData,
private dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>,
private aiResourceService: AiResourceService) {
constructor(protected store: Store<AppState>,
protected router: Router,
public dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData,
private aiResourceService: AiResourceService,
private translate: TranslateService,
private sanitizer: DomSanitizer) {
super(store, router, dialogRef);
this.preview$ = this.aiResourceService.getUrl(data.resource.id).pipe(
map(url => ({url})),
catchError(error => of({error: this.errorMessage(error)}))
);
}
download(): void {
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');
}
}

37
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<string>;
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<File> => {
if (!RESIZABLE_IMAGE_TYPES.includes(file.type)) {
if (!AI_IMAGE_MEDIA_TYPES.includes(file.type)) {
return file;
}
let image: HTMLImageElement;

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

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

62
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%);
}
}
}

66
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<string | null>;
}
@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<AiAttachmentItem>();
@Output() resourceError = new EventEmitter<any>();
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, AiAttachmentPreviewDialogData>(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);
}
}

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

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

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

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

50
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()">
<span class="return-glyph" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M20 4v7a4 4 0 0 1-4 4H4" pathLength="1"/><polyline points="9 10 4 15 9 20" pathLength="1"/></svg>
@ -65,7 +64,7 @@
@if (attachEnabled()) {
<button type="button" class="composer-tool composer-add"
[attr.aria-label]="'ai-assistant.add-files' | translate"
[tbAiTip]="addTip"
tb-popover [tbAiTip]="addTip"
(click)="openFilePicker()">
<mat-icon class="tb-mat-18">attach_file</mat-icon>
</button>
@ -73,8 +72,7 @@
<span class="composer-spacer"></span>
<button type="button" class="composer-tool"
[attr.aria-label]="'ai-assistant.shortcuts' | translate"
[tbAiTip]="keysTip"
tipClass="tip-keys"
tb-popover [tbAiTip]="keysTip"
[tipToggle]="true">
<mat-icon class="tb-mat-18">keyboard</mat-icon>
</button>
@ -83,30 +81,36 @@
</div>
<ng-template #sendTip>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
<div class="tb-ai-tip-body tip-mini">
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
</div>
</div>
</ng-template>
<ng-template #addTip>
<div class="tip-head"><b>{{ 'ai-assistant.add-files' | translate }}</b></div>
<p>{{ 'ai-assistant.add-files-text' | translate }}</p>
<p class="tip-sub">{{ 'ai-assistant.add-files-hint' | translate: {count: maxPerMessage(), size: maxSize()} }}</p>
<div class="tb-ai-tip-body">
<div class="tip-head"><b>{{ 'ai-assistant.add-files' | translate }}</b></div>
<p>{{ 'ai-assistant.add-files-text' | translate }}</p>
<p class="tip-sub">{{ 'ai-assistant.add-files-hint' | translate: {count: maxPerMessage(), size: maxSize()} }}</p>
</div>
</ng-template>
<ng-template #keysTip>
<div class="tip-head"><b>{{ 'ai-assistant.shortcuts' | translate }}</b></div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.new-line' | translate }}</span>
<span class="tip-caps"><kbd>Shift</kbd><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.focus-composer' | translate }}</span>
<span class="tip-caps"><kbd>/</kbd></span>
<div class="tb-ai-tip-body tip-keys">
<div class="tip-head"><b>{{ 'ai-assistant.shortcuts' | translate }}</b></div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span>
<span class="tip-caps"><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.new-line' | translate }}</span>
<span class="tip-caps"><kbd>Shift</kbd><kbd>Enter</kbd></span>
</div>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.focus-composer' | translate }}</span>
<span class="tip-caps"><kbd>/</kbd></span>
</div>
</div>
</ng-template>

129
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;
}
}
}

69
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<typeof setTimeout>;
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<void> {
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<void> {
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<PendingAttachment>): void {

238
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<unknown>;
private showTimer: ReturnType<typeof setTimeout>;
private hideTimer: ReturnType<typeof setTimeout>;
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<HTMLElement>>(ElementRef);
private injector = inject(Injector);
private zone = inject(NgZone);
@Input('tbAiTip') template: TemplateRef<unknown>;
private renderer = inject(Renderer2);
@Input() tipClass: string;
@Input('tbAiTip') template: TemplateRef<void>;
@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<unknown> {
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');
}
}

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

@ -57,7 +57,8 @@
<tb-ai-chat-messages
[messages]="messages()"
[loading]="loading()"
[loadingLongTime]="loadingLongTime()">
[loadingLongTime]="loadingLongTime()"
(resourceError)="showErrorMessage($event)">
<div loadingLongTime class="long-wait flex w-full flex-col items-center gap-6 rounded-xl">
<img [src]="loadingImage" alt="Loading">
<div class="flex flex-col items-center gap-1">

2
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();

4
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<AiResourceInfo, 'mediaType'>): boolean =>
['image/png', 'image/jpeg', 'image/webp'].includes(resource.mediaType);
AI_IMAGE_MEDIA_TYPES.includes(resource.mediaType);
export interface AiAssistantViewConfig {
listView: AiAssistantViewType;

2
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}}",

111
ui-ngx/src/styles.scss

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

Loading…
Cancel
Save