From 5d9c4237338e0d19af9b94d6b9970e84e1840caf Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Wed, 4 Nov 2026 16:11:46 +0200 Subject: [PATCH 001/183] feat: AI Assistant page: a menu item after IoT Hub opening the chats list (new chat, search, chats grouped by pinned and by day, rename, pin, delete) beside a reusable AI chat component (messages, composer, rename, fullscreen), the AI design tokens and shared AI styles applied to every AI component, and an auto-approve toggle in the composer --- ui-ngx/src/app/core/http/ai-chat.service.ts | 3 +- .../src/app/core/services/ai-chats.service.ts | 109 ++++ ui-ngx/src/app/core/services/menu.models.ts | 20 + .../ai/ai-approval-card.component.scss | 54 +- .../ai/ai-assistant-panel.component.html | 4 + .../ai/ai-assistant-panel.component.ts | 16 +- .../ai/ai-attachments.component.scss | 52 +- .../ai/ai-chat-messages.component.html | 11 +- .../ai/ai-chat-messages.component.scss | 99 ++-- .../ai/ai-chat-messages.component.ts | 49 +- .../home/components/ai/ai-chat.component.html | 92 ++++ .../home/components/ai/ai-chat.component.scss | 187 +++++++ .../home/components/ai/ai-chat.component.ts | 465 ++++++++++++++++++ .../ai/ai-credits-popup.component.scss | 17 +- .../components/ai/ai-credits.component.scss | 32 +- .../ai/ai-prompt-input.component.html | 15 + .../ai/ai-prompt-input.component.scss | 251 +++++++--- .../ai/ai-prompt-input.component.ts | 13 + .../modules/home/components/ai/ai.module.ts | 3 + .../ai-assistant-routing.module.ts | 32 ++ .../ai-assistant/ai-assistant.component.html | 127 +++++ .../ai-assistant/ai-assistant.component.scss | 452 +++++++++++++++++ .../ai-assistant/ai-assistant.component.ts | 239 +++++++++ .../pages/ai-assistant/ai-assistant.module.ts | 21 + .../modules/home/pages/home-pages.module.ts | 4 +- .../src/app/shared/models/ai-chat.models.ts | 6 + .../assets/locale/locale.constant-en_US.json | 25 +- ui-ngx/src/theme/ai-theme.scss | 380 ++++++++++++++ ui-ngx/src/theme/app-theme.scss | 1 + 29 files changed, 2570 insertions(+), 209 deletions(-) create mode 100644 ui-ngx/src/app/core/services/ai-chats.service.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts create mode 100644 ui-ngx/src/theme/ai-theme.scss diff --git a/ui-ngx/src/app/core/http/ai-chat.service.ts b/ui-ngx/src/app/core/http/ai-chat.service.ts index 76b343c072..3044f6a0e8 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -7,6 +7,7 @@ import { HttpClient, HttpEventType } from '@angular/common/http'; import { ApprovalResult, ChatConfiguration, + ChatUpdate, ChatEvent, ChatInfo, SendChatMessageRequest, @@ -33,7 +34,7 @@ export class AiChatService { return this.http.post(`/api/ai/chats`, chat, defaultHttpOptionsFromConfig(config)); } - public updatedChat(chatId: string, chat: ChatConfiguration, config?: RequestConfig): Observable { + public updatedChat(chatId: string, chat: ChatUpdate, config?: RequestConfig): Observable { return this.http.patch(`/api/ai/chats/${chatId}`, chat, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts new file mode 100644 index 0000000000..192dfab1aa --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable, signal } from '@angular/core'; +import { Observable, of } from 'rxjs'; +import { map, switchMap, tap } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { DialogService } from '@core/services/dialog.service'; +import { ChatInfo } from '@shared/models/ai-chat.models'; + +@Injectable({ providedIn: 'root' }) +export class AiChatsService { + + private aiChat = inject(AiChatService); + private panelService = inject(AiAssistantPanelService); + private dialog = inject(DialogService); + private translate = inject(TranslateService); + + private _chats = signal([]); + readonly chats = this._chats.asReadonly(); + + private _loaded = signal(false); + readonly loaded = this._loaded.asReadonly(); + + private _replying = signal>(new Set()); + readonly replying = this._replying.asReadonly(); + + load(): Observable { + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + tap({ + next: chats => { + this._chats.set(chats); + this._loaded.set(true); + this.panelService.setChats(chats); + }, + error: () => this._loaded.set(true) + }) + ); + } + + find(chatId: string | undefined): ChatInfo | undefined { + return chatId ? this._chats().find(chat => chat.id === chatId) : undefined; + } + + create(title: string): Observable { + return this.aiChat.createChat({title}, {ignoreLoading: true, ignoreErrors: true}).pipe( + map(id => ({id, title, createdTime: Date.now()} as ChatInfo)), + tap(chat => { + this._chats.update(list => [chat, ...list]); + if (this.panelService.chats() !== null) { + this.panelService.addChat(chat); + } + }) + ); + } + + rename(chatId: string, title: string): Observable { + return this.aiChat.updatedChat(chatId, {title}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.setTitle(chatId, title)) + ); + } + + setPinned(chatId: string, pinned: boolean): Observable { + return this.aiChat.updatedChat(chatId, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, pinned} : chat))) + ); + } + + setTitle(chatId: string, title: string): void { + this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat)); + this.panelService.updateChatTitle(chatId, title); + } + + confirmAndDelete(chat: ChatInfo): Observable { + const title = chat.title || this.translate.instant('ai-assistant.new-chat'); + return this.dialog.confirm( + this.translate.instant('ai-assistant.delete-chat-title', {name: title}), + this.translate.instant('ai-assistant.delete-chat-text'), + this.translate.instant('action.no'), + this.translate.instant('ai-assistant.delete-chat-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.aiChat.deleteChat(chat.id, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => { + this._chats.update(list => list.filter(c => c.id !== chat.id)); + this.panelService.removeChat(chat.id); + }), + map(() => true) + ) + : of(false)) + ); + } + + setReplying(chatId: string | undefined, replying: boolean): void { + if (!chatId) { + return; + } + this._replying.update(set => { + const next = new Set(set); + if (replying) { + next.add(chatId); + } else { + next.delete(chatId); + } + return next; + }); + } +} diff --git a/ui-ngx/src/app/core/services/menu.models.ts b/ui-ngx/src/app/core/services/menu.models.ts index 85316cf568..8f4ef82a74 100644 --- a/ui-ngx/src/app/core/services/menu.models.ts +++ b/ui-ngx/src/app/core/services/menu.models.ts @@ -178,6 +178,7 @@ export enum MenuId { secrets = 'secrets', ai_models = 'ai_models', iot_hub = 'iot_hub', + ai_assistant = 'ai_assistant', reporting = 'reporting', report_templates = 'report_templates', report_scheduling = 'report_scheduling', @@ -1551,6 +1552,18 @@ export const menuSectionMap = new Map([ outlinedIcon: 'mdi:hub-outline', isNew: true } + ], + [ + MenuId.ai_assistant, + { + id: MenuId.ai_assistant, + name: 'ai-assistant.ai-assistant', + type: 'link', + path: '/ai-assistant', + icon: 'auto_awesome', + outlinedIcon: 'mdi:creation-outline', + isNew: true + } ] ]); @@ -1587,6 +1600,12 @@ const menuFilters = new Map([ authState.authUser.authority === Authority.TENANT_ADMIN && userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL) ], + [ + MenuId.ai_assistant, (authState, userPermissionsService) => + authState.aiEnabled && + authState.authUser.authority === Authority.TENANT_ADMIN && + userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) + ], [ MenuId.device_all, (_authState, userPermissionsService) => userPermissionsService.hasReadGenericPermission(Resource.DEVICE) @@ -2008,6 +2027,7 @@ export const defaultUserMenuMap = new Map([ [ {id: MenuId.home}, {id: MenuId.iot_hub}, + {id: MenuId.ai_assistant}, {id: MenuId.ai_solution_creator}, { id: MenuId.monitor, diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss index 7e873c0de3..775051cbb9 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss @@ -2,43 +2,45 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - border: 1px solid rgba(0, 0, 0, 0.12); + border: 1px solid var(--k-stroke); border-radius: 12px; - padding: 16px; + padding: var(--chat-card-pad); + background: var(--tb-surface); + font-family: var(--tb-font); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); &.executing { - color: rgba(0, 0, 0, 0.76); + color: var(--k-grey); } &.approved { - color: #198038; - background-color: rgba(25, 128, 56, 0.06); + color: var(--tb-ok-text); + background-color: var(--tb-ok-tint); } &.denied { - color: rgba(0, 0, 0, 0.54); - background-color: rgba(0, 0, 0, 0.06); + color: var(--tb-text-secondary); + background-color: var(--tb-line-soft); } &.error { - color: #D12730; - background-color: rgba(209, 39, 48, 0.08); + color: var(--tb-crit); + background-color: var(--tb-crit-tint); } .approval-title { margin-bottom: 8px; font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; + font-size: var(--chat-head); + line-height: var(--chat-head-lh); } .approval-content { - font-size: 14px; - line-height: 20px; margin-bottom: 16px; - color: rgba(0, 0, 0, 0.54); - letter-spacing: 0.25px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); } .approval-actions { @@ -48,36 +50,36 @@ .approved { flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #198038; + --mat-button-filled-label-text-color: var(--ai-on-action); + --mat-button-filled-container-color: var(--ai-action); } .danger { flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #d32f2f; + --mat-button-filled-label-text-color: var(--ai-on-action); + --mat-button-filled-container-color: var(--tb-crit); } .denied { flex: 1; - --mat-button-outlined-label-text-color: #FF5722; + --mat-button-outlined-label-text-color: var(--tb-ink); + --mat-button-outlined-outline-color: var(--k-stroke-hover); } } .approve-all { width: 100%; margin-top: 8px; - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.54); - --mat-button-text-container-height: 32px; + --mat-button-text-label-text-color: var(--tb-text-secondary); + --mat-button-text-container-height: var(--chat-control); } .approval-result { display: flex; align-items: center; gap: 8px; - font-size: 16px; + font-size: var(--chat-line); font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; + line-height: var(--chat-line-lh); } } 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..5d395d79d6 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 @@ -102,6 +102,10 @@ [placeholder]="activePlaceholder()" [loading]="loading()" [dropZone]="chatContainer" + [showAutoApprove]="true" + [autoApprove]="autoApprove()" + [autoApproveInChat]="!!chatId()" + (autoApproveChange)="setAutoApprove($event)" (messageSent)="sendMsgFromUser($event)"> diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts index 9b68272d22..a9a7b8e259 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 @@ -96,7 +96,9 @@ export class AiAssistantPanelComponent implements OnInit { promptExamples = computed(() => this.panelService.config()?.promptExamples ?? []); - autoApprove = computed(() => this.panelService.isAutoApprove(this.chatId())); + newChatAutoApprove = signal(false); + + autoApprove = computed(() => this.chatId() ? this.panelService.isAutoApprove(this.chatId()) : this.newChatAutoApprove()); selectedChatTitle = computed(() => { const id = this.chatId(); @@ -221,6 +223,15 @@ export class AiAssistantPanelComponent implements OnInit { ).subscribe(); } + setAutoApprove(enabled: boolean): void { + const chatId = this.chatId(); + if (chatId) { + this.panelService.setAutoApprove(chatId, enabled); + } else { + this.newChatAutoApprove.set(enabled); + } + } + setMenuWidth(triggerEl: MatButton): void { const width = triggerEl._elementRef.nativeElement.offsetWidth; document.documentElement.style.setProperty('--chat-menu-dynamic-width', `${width}px`); @@ -366,6 +377,9 @@ export class AiAssistantPanelComponent implements OnInit { ? of(null) : this.aiChat.createChat({title: 'New chat'}, {ignoreLoading: true, ignoreErrors: true}).pipe( tap(chatId => { + if (this.newChatAutoApprove()) { + this.panelService.setAutoApprove(chatId, true); + } this.isCreatingNew.set(false); this.chatId.set(chatId); this.panelService.setLastChatId(chatId); 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..e169935786 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 @@ -16,8 +16,8 @@ display: flex; align-items: center; border-radius: 10px; - border: 1px solid rgba(0, 0, 0, 0.12); - background: #fff; + border: 1px solid var(--k-stroke); + background: var(--tb-surface); overflow: hidden; flex: none; @@ -25,7 +25,7 @@ cursor: pointer; &:hover { - border-color: var(--tb-primary-500); + border-color: var(--ai-focus); } } @@ -33,7 +33,7 @@ width: 64px; height: 64px; justify-content: center; - background: rgba(0, 0, 0, 0.04); + background: var(--tb-line-soft); img { width: 100%; @@ -42,7 +42,7 @@ } .placeholder { - color: rgba(0, 0, 0, 0.38); + color: var(--tb-ink-38); } } @@ -60,22 +60,13 @@ width: 32px; height: 32px; border-radius: 8px; - color: var(--tb-primary-500); - position: relative; - - &:before { - content: ""; - position: absolute; - inset: 0; - border-radius: inherit; - background: var(--tb-primary-500); - opacity: 0.1; - } + color: var(--ai-selected-text); + background: var(--ai-selected-wash); mat-icon { - font-size: 20px; - width: 20px; - height: 20px; + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); } } @@ -83,26 +74,27 @@ display: flex; flex-direction: column; min-width: 0; - line-height: 16px; + line-height: var(--chat-meta-lh); .file-name { - font-size: 13px; - color: rgba(0, 0, 0, 0.87); + font-size: var(--chat-meta); + font-weight: 500; + color: var(--tb-ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .file-info { - font-size: 11px; - color: rgba(0, 0, 0, 0.54); + font-size: var(--chat-caption); + color: var(--k-faint); white-space: nowrap; } } } &.failed { - border-color: rgba(209, 39, 48, 0.6); + border-color: color-mix(in srgb, var(--tb-crit) 60%, transparent); } .state { @@ -111,10 +103,10 @@ display: flex; align-items: center; justify-content: center; - background: rgba(255, 255, 255, 0.7); + background: color-mix(in srgb, var(--tb-surface) 70%, transparent); .error-icon { - color: rgb(209, 39, 48); + color: var(--tb-crit); } } @@ -131,13 +123,13 @@ align-items: center; justify-content: center; cursor: pointer; - color: #fff; - background: rgba(0, 0, 0, 0.6); + color: var(--ai-on-dark); + background: color-mix(in srgb, var(--ai-dark) 80%, transparent); opacity: 0.9; &:hover { opacity: 1; - background: rgba(0, 0, 0, 0.8); + background: var(--ai-dark); } mat-icon { 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..5523b3295e 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 @@ -29,19 +29,20 @@ {{ msg.content }} } @else { - +
+ + +
} } } @if (loading && !waitApproval) { -
+
@if (loadingLongTime) { } @else { - - - +
{{ 'ai-assistant.thinking' | translate }}
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index c9b42e734e..43d8af9003 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -3,16 +3,17 @@ :host { display: flex; flex-direction: column; - gap: 24px; + gap: var(--chat-turn-gap); overflow: auto; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); width: 100%; margin-top: 8px; flex: 1 1 auto; - .image-main-color { - color: var(--tb-primary-500); - } - .user { display: flex; flex-direction: column; @@ -34,52 +35,66 @@ .msg { max-width: 80%; - padding: 10px 18px; - border-radius: 12px 12px 0 12px; - position: relative; + padding: 12px 16px; + border-radius: 16px 16px 4px 16px; + background: var(--ai-person); overflow: hidden; white-space: pre-line; word-break: break-word; - line-height: 24px; - color: rgba(0, 0, 0, 0.76); + color: var(--tb-ink); + } + } - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; - } + .agent { + display: flex; + align-items: flex-start; + gap: 10px; + + .tb-ai-mark { + --m: var(--chat-mark); + margin-top: 2px; + } + + .agent-body { + flex: 1; + min-width: 0; + padding-top: 2px; } } .incomplete { padding: 10px 14px; border-radius: 12px; - line-height: 20px; - color: rgba(0, 0, 0, 0.76); - background: rgba(255, 152, 0, 0.08); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + background: var(--tb-caution-tint); .incomplete-icon { flex: none; - color: #FF9800; - font-size: 20px; - width: 20px; - height: 20px; + color: var(--tb-caution); + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); } } .generating { + gap: 10px; + + .tb-ai-mark { + --m: var(--chat-mark); + } + + font-size: var(--chat-line); + line-height: var(--chat-line-lh); transition: all 0.3s ease-in-out; .glow-container { color: transparent; overflow: hidden; position: relative; - background: linear-gradient(90deg, #3D3D3D -40.76%, #808080 -23.64%, #3D3D3D -6.52%); + background: linear-gradient(90deg, var(--tb-ink-76) -40.76%, var(--tb-ink-38) -23.64%, var(--tb-ink-76) -6.52%); background-clip: text; animation: fadeInScale 0.3s ease-in-out forwards; opacity: 0; @@ -99,7 +114,7 @@ height: 100%; flex-shrink: 0; opacity: 0.5; - background: #FFF; + background: var(--tb-surface); filter: blur(2px); transform: skewX(-25deg); animation: glow-move 3s ease-in-out infinite; @@ -123,20 +138,34 @@ &::ng-deep { .tb-markdown-view { + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink); + h2 { - font-size: 28px; + font-size: var(--chat-title); + line-height: var(--chat-title-lh); } h3 { - font-size: 24px; + font-size: 20px; + line-height: 28px; } - h4 { - font-size: 20px; + h4, h5, h6 { + font-size: var(--chat-head); + line-height: var(--chat-head-lh); } - h5, h6 { - font-size: 18px; + code { + font-family: var(--tb-mono); + font-size: var(--chat-code); + } + + a { + color: var(--ai-link); + text-decoration-color: var(--ai-link-line); } a { 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..e837fc06b4 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 @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, ElementRef, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; +import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; @@ -10,7 +10,7 @@ import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@sh styleUrls: ['./ai-chat-messages.component.scss'], standalone: false }) -export class AiChatMessagesComponent implements OnChanges { +export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() messages: ChatMessage[] = []; @Input() loading = false; @@ -18,10 +18,16 @@ export class AiChatMessagesComponent implements OnChanges { @Input() additionalStyles: string[]; @Input() completedExecutions: Record = {}; @Input() autoApprove = false; + @Input() scrollContainer: HTMLElement; + @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; @Output() approvalAction = new EventEmitter(); waitApproval = false; + private static readonly PIN_TO_BOTTOM_MS = 1500; + + private releaseBottom: () => void; + constructor(private elementRef: ElementRef) {} getApprovalData(msg: ApprovalChatMessage): ToolExecutionRequested { @@ -40,7 +46,11 @@ export class AiChatMessagesComponent implements OnChanges { } if (changes.messages) { if (changes.messages.firstChange) { - setTimeout(() => this.scrollToLastUserMessage(), 0); + if (this.initialScroll === 'bottom') { + this.pinToBottom(); + } else { + setTimeout(() => this.scrollToLastUserMessage(), 0); + } return; } const wasNearBottom = this.isNearBottom(); @@ -77,8 +87,33 @@ export class AiChatMessagesComponent implements OnChanges { this.approvalAction.emit($event); } + ngOnDestroy(): void { + this.releaseBottom?.(); + } + + private pinToBottom(): void { + const scroller = this.scroller; + const stick = () => scroller.scrollTop = scroller.scrollHeight; + const observer = new ResizeObserver(stick); + observer.observe(this.elementRef.nativeElement); + const release = () => { + observer.disconnect(); + clearTimeout(timeout); + scroller.removeEventListener('wheel', release); + scroller.removeEventListener('touchstart', release); + scroller.removeEventListener('keydown', release); + this.releaseBottom = undefined; + }; + const timeout = setTimeout(release, AiChatMessagesComponent.PIN_TO_BOTTOM_MS); + scroller.addEventListener('wheel', release, {passive: true}); + scroller.addEventListener('touchstart', release, {passive: true}); + scroller.addEventListener('keydown', release); + this.releaseBottom = release; + stick(); + } + scrollToBottom(behavior: ScrollBehavior = 'smooth'): void { - const el = this.elementRef.nativeElement; + const el = this.scroller; el.scrollTo({top: el.scrollHeight, behavior}); } @@ -118,8 +153,12 @@ export class AiChatMessagesComponent implements OnChanges { } } + private get scroller(): HTMLElement { + return this.scrollContainer ?? this.elementRef.nativeElement; + } + private isNearBottom(threshold = 150): boolean { - const el = this.elementRef.nativeElement; + const el = this.scroller; return el.scrollHeight - el.scrollTop - el.clientHeight <= threshold; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html new file mode 100644 index 0000000000..6c93028a22 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -0,0 +1,92 @@ + +
+ + @if (variant() === 'panel') { + + } + @if (chat(); as chat) { + @if (renaming()) { + + } @else { + {{ chat.title }} + } + } @else { + {{ 'ai-assistant.new-chat' | translate }} + } +
+ @if (fullscreenEnabled()) { + + } + @if (chat() && !renaming()) { + + } + +
+
+
+
+ @if (messages().length || loading()) { + + + } @else if (!chatId()) { +
+ +

{{ 'ai-assistant.what-to-work-on' | translate }}

+
+ } +
+ + +
+
+ + + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss new file mode 100644 index 0000000000..e145531ec1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -0,0 +1,187 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + position: relative; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.ai-chat-head { + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid var(--tb-line-soft); +} + +:host(.v-panel) .ai-chat-head { + height: 52px; + gap: 10px; + padding: 6px 8px 6px 12px; +} + +.ai-chat-name { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 500 15px/20px var(--tb-font); + color: var(--tb-ink); +} + +:host(.v-panel) .ai-chat-name { + font-size: var(--chat-line); +} + +.ai-chat-rename { + flex: 1; + min-width: 0; + max-width: 480px; + height: 30px; + box-sizing: border-box; + padding: 0 8px; + border: 0; + border-radius: 8px; + outline: 0; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1.5px var(--ai-teal-500); + font: 500 15px/20px var(--tb-font); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); +} + +.ai-chat-actions { + flex: none; + display: flex; + align-items: center; + gap: 2px; +} + +:host ::ng-deep .ai-ib { + position: relative; + flex: none; + width: 32px; + height: 32px; + min-width: var(--chat-tap); + min-height: var(--chat-tap); + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: 19px; + width: 19px; + height: 19px; + } +} + +:host(.v-panel) ::ng-deep .ai-ib { + width: 28px; + height: 28px; +} + +.ai-chat-body { + position: relative; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + align-items: center; + overflow-y: auto; + padding: 20px 20px 0; + + &.empty { + justify-content: center; + padding-bottom: 12vh; + } +} + +:host(.v-panel) .ai-chat-body { + padding: 16px 16px 0; + + &.empty { + padding-bottom: 8vh; + } +} + +.ai-chat-log { + flex: 1 0 auto; + width: 100%; + max-width: 760px; + margin-top: 0; + overflow: visible; +} + +.ai-chat-start { + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + text-align: center; +} + +.ai-chat-start-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); +} + +.ai-chat-composer { + position: sticky; + bottom: 0; + z-index: 1; + flex: none; + width: 100%; + max-width: 760px; + padding: 12px 0 14px; + background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); +} + +.ai-chat-body.empty .ai-chat-composer { + position: static; + max-width: 680px; + padding-top: 20px; + background: none; +} + +@media (max-width: 599px) { + .ai-chat-body { + padding: 16px 16px 0; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts new file mode 100644 index 0000000000..2fffca8bee --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -0,0 +1,465 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + input, + model, + OnDestroy, + OnInit, + SecurityContext, + signal, + untracked, + ViewChild +} from '@angular/core'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; +import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; +import { + AiChatClientContext, + AiPromptMessage, + ApprovalResult, + ChatEvent, + SendChatMessageRequest, + ToolExecutionRequestedEvent, + ToolExecutionResult +} from '@shared/models/ai-chat.models'; +import { EntityId } from '@shared/models/id/entity-id'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; + +export type AiChatVariant = 'page' | 'panel'; + +@Component({ + selector: 'tb-ai-chat', + templateUrl: './ai-chat.component.html', + styleUrls: ['./ai-chat.component.scss'], + standalone: false, + host: { + 'data-ai': '', + '[attr.data-type]': 'variant() === "panel" ? "compact" : null', + '[attr.data-space]': 'variant() === "panel" ? "compact" : null', + 'class': 'tb-ai-chat', + '[class.v-page]': 'variant() === "page"', + '[class.v-panel]': 'variant() === "panel"' + } +}) +export class AiChatComponent implements OnInit, OnDestroy { + + private static readonly RESUME_ATTEMPTS = 4; + private static readonly RESUME_DELAY_MS = 2000; + + @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + + chatId = model(undefined); + + variant = input('page'); + + clientContext = input(undefined); + + toastTarget = input('aiChat'); + + fullscreenEnabled = input(true); + + fullscreen = signal(false); + + readonly markdownStyles = [ + '.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;}' + ]; + + messages = signal([]); + + loading = signal(false); + + completedExecutions = signal>({}); + + renaming = signal(false); + + nameClipped = signal(false); + + chat = computed(() => { + const id = this.chatId(); + return id ? this.chats.chats().find(chat => chat.id === id) : undefined; + }); + + newChatAutoApprove = signal(false); + + autoApprove = computed(() => this.chatId() ? this.panelService.isAutoApprove(this.chatId()) : this.newChatAutoApprove()); + + placeholder = computed(() => this.translate.instant(this.messages().length + ? 'ai-assistant.follow-up-prompt-placeholder' + : 'ai-assistant.prompt-placeholder')); + + private aiChat = inject(AiChatService); + private chats = inject(AiChatsService); + private panelService = inject(AiAssistantPanelService); + private translate = inject(TranslateService); + private store = inject(Store); + private sanitizer = inject(DomSanitizer); + private destroyRef = inject(DestroyRef); + private host = inject>(ElementRef); + + readonly hostElement = this.host.nativeElement; + + private loadChat$ = new Subject(); + private cancelMessage$ = new Subject(); + private messageCancelled = false; + private shownChatId: string | undefined; + private replyingChatId: string | undefined; + private affectedEntities: EntityId[] = []; + private logScrollBottom: number | undefined; + + private chatIdEffect = effect(() => { + const chatId = this.chatId(); + untracked(() => this.show(chatId)); + }); + + private deletedChatEffect = effect(() => { + const chatId = this.chatId(); + if (chatId && this.chats.loaded() && !this.chats.find(chatId)) { + untracked(() => this.chatId.set(undefined)); + } + }); + + ngOnInit(): void { + this.loadChat$.pipe( + switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( + catchError(err => { + this.showErrorMessage(err); + return EMPTY; + }) + )), + takeUntilDestroyed(this.destroyRef) + ).subscribe(messages => { + this.showHistory(messages); + this.resumeTurn(this.chatId()); + }); + } + + ngOnDestroy(): void { + this.cancelActiveMessage(); + } + + toggleFullscreen(): void { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + this.logScrollBottom = log ? log.scrollHeight - log.clientHeight - log.scrollTop : undefined; + this.fullscreen.set(!this.fullscreen()); + } + + onFullscreenChanged(fullscreen: boolean): void { + this.fullscreen.set(fullscreen); + const scrollBottom = this.logScrollBottom; + if (scrollBottom !== undefined) { + setTimeout(() => { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + if (log) { + log.scrollTop = log.scrollHeight - log.clientHeight - scrollBottom; + } + }); + } + } + + focus(): void { + this.promptInput?.focus(); + } + + startRename(): void { + if (!this.chat()) { + return; + } + this.renaming.set(true); + setTimeout(() => { + const input = this.host.nativeElement.querySelector('.ai-chat-rename'); + input?.focus(); + input?.select(); + }); + } + + onRenameKeydown(event: KeyboardEvent): void { + if (event.isComposing) { + return; + } + if (event.key === 'Enter') { + (event.target as HTMLInputElement).blur(); + } else if (event.key === 'Escape') { + this.renaming.set(false); + } + } + + finishRename(value: string): void { + const chat = this.chat(); + if (!this.renaming() || !chat) { + return; + } + this.renaming.set(false); + const title = value.trim(); + if (title && title !== chat.title) { + this.chats.rename(chat.id, title).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + togglePinned(): void { + const chat = this.chat(); + if (chat) { + this.chats.setPinned(chat.id, !chat.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + deleteChat(): void { + const chat = this.chat(); + if (chat) { + this.chats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + setAutoApprove(enabled: boolean): void { + const chatId = this.chatId(); + if (chatId) { + this.panelService.setAutoApprove(chatId, enabled); + } else { + this.newChatAutoApprove.set(enabled); + } + } + + onApprovalAction(event: ApprovalResult): void { + const chatId = this.chatId(); + if (event.autoApprove && chatId) { + this.panelService.setAutoApprove(chatId, true); + } + this.aiChat.resolveToolApproval( + {executionId: event.executionId, approved: event.approved}, + {ignoreLoading: true, ignoreErrors: true} + ).subscribe(); + } + + sendMsgFromUser(prompt: AiPromptMessage): void { + const userMessage: ChatMessage = prompt.resources.length + ? {from: 'USER', content: prompt.message, resources: prompt.resources} + : {from: 'USER', content: prompt.message}; + this.messages.update(list => [...list, userMessage]); + this.sendMessage(prompt).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.showErrorToast(this.translate.instant('ai-assistant.connection-lost')); + this.resumeTurn(this.chatId(), true); + return; + } + this.messages.update(list => list.filter(message => message !== userMessage)); + setTimeout(() => this.showErrorMessage(err), 0); + } + }); + } + + private show(chatId: string | undefined): void { + if (chatId === this.shownChatId) { + return; + } + this.cancelActiveMessage(); + this.renaming.set(false); + this.shownChatId = chatId; + this.messages.set([]); + this.completedExecutions.set({}); + if (chatId) { + this.loadChat$.next(chatId); + } else { + setTimeout(() => this.promptInput?.focus()); + } + } + + private sendMessage(prompt: AiPromptMessage): Observable { + this.messageCancelled = false; + const startOrContinue$ = this.chatId() + ? of(null) + : this.chats.create('New chat').pipe( + tap(chat => { + if (this.newChatAutoApprove()) { + this.panelService.setAutoApprove(chat.id, true); + } + this.shownChatId = chat.id; + this.chatId.set(chat.id); + }) + ); + const request: SendChatMessageRequest = {message: prompt.message}; + if (prompt.resources.length) { + request.resources = prompt.resources.map(resource => resource.id); + } + if (this.clientContext()) { + request.clientContext = this.clientContext(); + } + this.loading.set(true); + return startOrContinue$.pipe( + tap(() => this.startLoading()), + switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), + takeUntil(this.cancelMessage$), + concatMap(event => this.handleChatEvent(event)), + finalize(() => this.stopLoading()) + ); + } + + private resumeTurn(chatId: string, afterConnectionLoss = false): void { + if (!chatId) { + return; + } + let resumed = false; + this.messageCancelled = false; + const attempt$ = timer(afterConnectionLoss ? AiChatComponent.RESUME_DELAY_MS : 0).pipe( + tap(() => { + if (afterConnectionLoss) { + this.startLoading(); + } + }), + switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) + ); + attempt$.pipe( + retry({ + count: afterConnectionLoss ? AiChatComponent.RESUME_ATTEMPTS : 0, + delay: (error, attempt) => this.isConnectionLost(error) + ? timer(attempt * AiChatComponent.RESUME_DELAY_MS) + : throwError(() => error) + }), + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'turnResumed') { + resumed = true; + this.startLoading(); + this.dropRunningReply(); + return of(event); + } + return this.handleChatEvent(event); + }), + finalize(() => { + if (resumed || afterConnectionLoss) { + this.stopLoading(); + } + }) + ).subscribe({ + error: () => { + if (afterConnectionLoss) { + this.showErrorToast(this.translate.instant('ai-assistant.reconnect-failed')); + } + }, + complete: () => { + if (this.messageCancelled || this.chatId() !== chatId) { + return; + } + if (resumed || afterConnectionLoss) { + this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) + .pipe(takeUntil(this.cancelMessage$)) + .subscribe(messages => this.showHistory(messages)); + } + } + }); + } + + private handleChatEvent(event: ChatEvent): Observable { + switch (event.event) { + case 'assistantMessage': + this.messages.update(list => [...list, {from: 'AI', content: event.data.message}]); + break; + case 'toolExecutionRequested': + this.handleToolApproval(event); + break; + case 'toolExecutionResult': + this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data})); + if (event.data.affectedEntities?.length) { + this.affectedEntities.push(...event.data.affectedEntities); + } + break; + case 'chatTitleGenerated': + if (this.chatId() && event.data.title) { + this.chats.setTitle(this.chatId(), event.data.title); + } + break; + default: + if (event.event === 'error') { + this.showErrorToast(this.sanitizer.sanitize(SecurityContext.HTML, event.data?.message) ?? event.data?.message); + } + } + return of(event); + } + + private handleToolApproval(event: ToolExecutionRequestedEvent): void { + if (event.data.needsApproval) { + this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]); + } + } + + private showHistory(messages: ChatMessage[]): void { + const completed: Record = {}; + for (const message of messages) { + const result = message.from === 'APPROVAL' ? (message as ApprovalChatMessage).result : undefined; + if (result) { + completed[result.executionId] = result; + } + } + this.completedExecutions.set(completed); + this.messages.set(messages); + } + + private dropRunningReply(): void { + this.messages.update(list => { + const lastUser = list.map(message => message.from).lastIndexOf('USER'); + return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; + }); + } + + private cancelActiveMessage(): void { + this.messageCancelled = true; + this.cancelMessage$.next(); + this.stopLoading(); + this.promptInput?.reset(); + } + + private startLoading(): void { + this.loading.set(true); + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = this.chatId(); + this.chats.setReplying(this.replyingChatId, true); + } + + private stopLoading(): void { + this.loading.set(false); + if (this.affectedEntities.length) { + this.panelService.emitUpdatedData(this.affectedEntities); + this.affectedEntities = []; + } + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = undefined; + } + + private isConnectionLost(error: any): boolean { + return error instanceof HttpErrorResponse && error.status === 0; + } + + private showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + this.showErrorToast(parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message); + } + + private showErrorToast(message: string): void { + this.store.dispatch(new ActionNotificationShow({ + message, + target: this.toastTarget(), + modern: true, + type: 'error', + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss index 371f0a9ebd..37f87a3ea3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss @@ -8,23 +8,22 @@ } .popup-title { - font-size: 16px; + font-size: var(--chat-head); font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.87); + line-height: var(--chat-head-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); } .popup-description { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--k-grey); margin: 0; strong { font-weight: 500; - letter-spacing: 0.25px; } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss index 52b4e60781..ff0764d57c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss @@ -3,27 +3,27 @@ :host { .ai-credits-donut, .mat-mdc-icon-button { - --_donut-color: #198038; - --_donut-track: rgba(0, 0, 0, 0.12); + --_donut-color: var(--tb-ok); + --_donut-track: var(--tb-ink-12); &.WARNING { - --_donut-color: #FAA405; - --_donut-track: rgba(250, 164, 5, 0.2); + --_donut-color: var(--tb-caution); + --_donut-track: var(--tb-caution-tint); } &.DISABLED { - --_donut-color: #D12730; - --_donut-track: rgba(209, 39, 48, 0.2); + --_donut-color: var(--tb-crit); + --_donut-track: color-mix(in srgb, var(--tb-crit) 20%, transparent); } } .ai-credits-donut { &:hover { - background-color: rgba(0, 0, 0, 0.04); + background-color: var(--tb-line-soft); } &:focus-visible { - outline: 2px solid var(--tb-primary-500, #00695c); + outline: 2px solid var(--ai-focus); outline-offset: 2px; } @@ -32,22 +32,22 @@ } .donut-title { - font-size: 14px; + font-size: var(--chat-line); font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--k-grey); } .donut-usage { - font-size: 13px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); } } .update-btn { - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.12); + --mat-button-outlined-outline-color: var(--k-stroke); --mat-button-outlined-horizontal-padding: 12px; } } 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..5ccc8d29ab 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 @@ -70,6 +70,13 @@ attach_file } + @if (showAutoApprove) { + + } +
+ + + +
+ } @else { +
+ + + +
+ } + + + + @if (!railOpen()) { + + } + + + + + + + + + diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss new file mode 100644 index 0000000000..8225209a04 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -0,0 +1,452 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + position: relative; + display: flex; + width: 100%; + height: 100%; + min-height: 0; + overflow: hidden; + background: #f4f6f7; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); +} + +.ai-rail .ai-ib, .ai-bar-chats { + position: relative; + flex: none; + width: 32px; + height: 32px; + min-width: var(--chat-tap); + min-height: var(--chat-tap); + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-60); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: 19px; + width: 19px; + height: 19px; + } +} + +.ai-panel-icon { + width: 20px; + height: 20px; + fill: currentColor; +} + +.ai-rail { + flex: none; + display: flex; + flex-direction: column; + width: 48px; + min-height: 0; +} + +:host(.rail-open) .ai-rail { + width: 256px; +} + +.ai-strip { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 14px 0 10px; +} + +.ai-rail-panel { + height: 100%; + display: flex; + flex-direction: column; + box-sizing: border-box; + padding: 8px 6px 10px 10px; +} + +.ai-rail-head { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 44px; + box-sizing: border-box; + margin-right: 4px; + padding-left: 8px; + + h2 { + margin: 0; + font: 500 var(--chat-head)/22px var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); + } +} + +.ai-nav { + display: grid; + grid-template-columns: 20px minmax(0, 1fr); + align-items: center; + gap: 10px; + width: calc(100% - 4px); + margin-right: 4px; + padding: 6px 10px 6px 8px; + border: 0; + border-radius: 8px; + background: none; + font: 500 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + text-align: left; + cursor: pointer; + transition: background-color .12s ease; + + .mat-icon { + font-size: 19px; + width: 20px; + height: 19px; + text-align: center; + color: var(--tb-ink-60); + } + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &.active { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + + .mat-icon { + color: var(--tb-ink); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.ai-find { + display: flex; + align-items: center; + gap: 10px; + height: 32px; + margin: 2px 4px 0 0; + padding: 0 10px 0 8px; + border-radius: 8px; + cursor: text; + transition: background-color .12s ease, box-shadow .12s ease; + + .mat-icon { + flex: none; + font-size: 19px; + width: 20px; + height: 19px; + text-align: center; + color: var(--tb-ink-60); + } + + input { + flex: 1; + min-width: 0; + padding: 0; + border: 0; + outline: 0; + background: none; + font: 400 13.5px/18px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + + &::placeholder { + color: var(--tb-ink-60); + } + + &::-webkit-search-cancel-button { + display: none; + } + } + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &.on { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + } + + &:focus-within { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke-hover); + + .mat-icon { + color: var(--tb-ink); + } + + .ai-find-key { + visibility: hidden; + } + } +} + +.ai-find-key { + flex: none; + padding: 0 5px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.05); + font: 500 11px/18px var(--tb-font); + color: var(--k-faint); + + @media (max-width: 599px), (pointer: coarse) { + display: none; + } +} + +.ai-find-clear { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + margin-right: -4px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } +} + +.ai-list { + flex: 1; + min-height: 0; + overflow-y: auto; + margin-top: 4px; + padding-right: 4px; +} + +.ai-sect { + margin-top: 18px; + + &:first-child { + margin-top: 12px; + } + + h3 { + margin: 0 8px 4px; + font: 500 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: 0.1px; + color: var(--tb-ink-54); + } +} + +.ai-row { + position: relative; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + column-gap: 8px; + min-height: 34px; + box-sizing: border-box; + padding: 7px 8px; + border-radius: 8px; + cursor: pointer; + transition: background-color .12s ease; + + &:hover { + background: rgba(0, 0, 0, 0.045); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.active { + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--k-stroke); + + .ai-row-title { + font-weight: 500; + } + } + + &.editing { + grid-template-columns: minmax(0, 1fr); + padding: 2px; + cursor: default; + } + + &:hover, &:focus-within { + .tb-ai-status-mark { + visibility: hidden; + } + + .ai-row-menu { + opacity: 1; + } + } + + .tb-ai-status-mark { + margin-right: 2px; + } +} + +.ai-row-title { + display: block; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 400 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + +.ai-row-menu { + position: absolute; + top: 50%; + right: 4px; + transform: translateY(-50%); + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + padding: 0; + border: 0; + border-radius: 8px; + background: var(--tb-surface); + color: var(--tb-ink-60); + cursor: pointer; + opacity: 0; + transition: opacity .12s ease; + + &:hover { + color: var(--tb-ink); + } + + &:focus-visible, &[aria-expanded="true"] { + opacity: 1; + } + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.ai-rename { + width: 100%; + height: 30px; + box-sizing: border-box; + padding: 0 8px; + border: 0; + border-radius: 8px; + outline: 0; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1.5px var(--ai-teal-500); + font: 400 13.5px/19px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + +.ai-empty { + margin: 16px 10px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); +} + +.ai-canvas { + flex: 1; + margin: 8px 8px 8px 0; + border-radius: 12px; + box-shadow: var(--tb-soft-shadow); + overflow: hidden; +} + +.ai-canvas .ai-bar-chats { + display: none; + margin-left: -8px; +} + +@media (max-width: 899px) { + :host(.rail-open) .ai-rail { + position: absolute; + z-index: 40; + top: 0; + bottom: 0; + left: 0; + background: #f4f6f7; + box-shadow: 8px 0 24px rgba(0, 0, 0, 0.12); + } + + :host(.rail-open) .ai-canvas { + margin-left: 48px; + + &::after { + content: ''; + position: absolute; + inset: 0; + z-index: 30; + border-radius: inherit; + background: rgba(16, 24, 40, 0.24); + cursor: pointer; + } + } +} + +@media (max-width: 599px) { + .ai-rail { + display: none; + } + + :host(.rail-open) .ai-rail { + display: flex; + width: min(300px, 86vw); + } + + .ai-canvas, :host(.rail-open) .ai-canvas { + margin: 0; + border-radius: 0; + box-shadow: none; + } + + .ai-canvas .ai-bar-chats { + display: inline-flex; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts new file mode 100644 index 0000000000..6e41341ae5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + Component, + computed, + effect, + ElementRef, + HostListener, + inject, + OnInit, + signal, + ViewChild +} from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { ChatInfo } from '@shared/models/ai-chat.models'; +import { DAY, WEEK } from '@shared/models/time/time.models'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; + +export interface AiChatsGroup { + label: string; + chats: ChatInfo[]; +} + +@Component({ + selector: 'tb-ai-assistant', + templateUrl: './ai-assistant.component.html', + styleUrls: ['./ai-assistant.component.scss'], + standalone: false, + host: { + 'data-ai': '', + '[class.rail-open]': 'railOpen()' + } +}) +export class AiAssistantComponent implements OnInit { + + private static readonly RAIL_OPEN_KEY = 'tbAiAssistantRailOpen'; + private static readonly NARROW_WIDTH = 900; + + @ViewChild(AiChatComponent) chat: AiChatComponent; + @ViewChild('searchInput') searchInput: ElementRef; + + readonly toastTarget = 'aiAssistantPage'; + + readonly shortcutModifier = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl '; + + railOpen = signal(this.initialRailOpen()); + + query = signal(''); + + renamingId = signal(null); + + chatId = signal(undefined); + + aiChats = inject(AiChatsService); + + groups = computed(() => { + const query = this.query().trim().toLowerCase(); + const chats = this.aiChats.chats(); + if (query) { + const found = chats.filter(chat => (chat.title ?? '').toLowerCase().includes(query)); + return found.length + ? [{label: this.translate.instant('ai-assistant.chats-found', {count: found.length}), chats: found}] + : []; + } + const now = new Date(); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + const groups: AiChatsGroup[] = [ + {label: this.translate.instant('ai-assistant.pinned'), chats: []}, + {label: this.translate.instant('ai-assistant.today'), chats: []}, + {label: this.translate.instant('ai-assistant.yesterday'), chats: []}, + {label: this.translate.instant('ai-assistant.last-7-days'), chats: []}, + {label: this.translate.instant('ai-assistant.older'), chats: []} + ]; + for (const chat of chats) { + const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4; + groups[index].chats.push(chat); + } + return groups.filter(group => group.chats.length); + }); + + private translate = inject(TranslateService); + private store = inject(Store); + private sanitizer = inject(DomSanitizer); + private router = inject(Router); + private route = inject(ActivatedRoute); + private host = inject>(ElementRef); + + private urlEffect = effect(() => { + const chatId = this.chatId() ?? null; + if (this.route.snapshot.queryParamMap.get('chatId') !== chatId && this.aiChats.loaded()) { + this.router.navigate([], { + relativeTo: this.route, + queryParams: {chatId}, + queryParamsHandling: 'merge', + replaceUrl: true + }); + } + }); + + ngOnInit(): void { + this.aiChats.load().subscribe({ + next: chats => { + const chatId = this.route.snapshot.queryParamMap.get('chatId'); + if (chatId && chats.some(chat => chat.id === chatId)) { + this.chatId.set(chatId); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + @HostListener('document:keydown', ['$event']) + onDocumentKeydown(event: KeyboardEvent): void { + if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key.toLowerCase() === 'k') { + event.preventDefault(); + this.openSearch(); + } + } + + toggleRail(): void { + this.setRailOpen(!this.railOpen()); + } + + openSearch(): void { + this.setRailOpen(true); + setTimeout(() => this.searchInput?.nativeElement.focus()); + } + + onSearchKeydown(event: KeyboardEvent): void { + if (event.key === 'Escape') { + event.preventDefault(); + if (this.query()) { + this.query.set(''); + } else { + (event.target as HTMLInputElement).blur(); + } + } + } + + onChatClick(event: MouseEvent): void { + if (event.target === event.currentTarget) { + this.settleRail(); + } + } + + newChat(): void { + this.settleRail(); + this.chatId.set(undefined); + setTimeout(() => this.chat?.focus()); + } + + selectChat(chat: ChatInfo): void { + this.settleRail(); + this.chatId.set(chat.id); + } + + startRename(chat: ChatInfo): void { + this.setRailOpen(true); + this.renamingId.set(chat.id); + setTimeout(() => { + const input = this.host.nativeElement.querySelector('.ai-rename'); + input?.focus(); + input?.select(); + }); + } + + onRenameKeydown(event: KeyboardEvent): void { + if (event.isComposing) { + return; + } + if (event.key === 'Enter') { + (event.target as HTMLInputElement).blur(); + } else if (event.key === 'Escape') { + this.renamingId.set(null); + } + } + + finishRename(chat: ChatInfo, value: string): void { + if (this.renamingId() !== chat.id) { + return; + } + this.renamingId.set(null); + const title = value.trim(); + if (title && title !== chat.title) { + this.aiChats.rename(chat.id, title).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + togglePinned(chat: ChatInfo): void { + this.aiChats.setPinned(chat.id, !chat.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + + deleteChat(chat: ChatInfo): void { + this.aiChats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); + } + + private setRailOpen(open: boolean): void { + this.railOpen.set(open); + try { + sessionStorage.setItem(AiAssistantComponent.RAIL_OPEN_KEY, open ? '1' : '0'); + } catch { + return; + } + } + + private settleRail(): void { + if (this.railOpen() && window.innerWidth < AiAssistantComponent.NARROW_WIDTH) { + this.setRailOpen(false); + } + } + + private initialRailOpen(): boolean { + try { + const stored = sessionStorage.getItem(AiAssistantComponent.RAIL_OPEN_KEY); + return stored === null ? window.innerWidth >= AiAssistantComponent.NARROW_WIDTH : stored === '1'; + } catch { + return true; + } + } + + private showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + this.store.dispatch(new ActionNotificationShow({ + message: parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message, + target: this.toastTarget, + modern: true, + type: 'error', + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts new file mode 100644 index 0000000000..c59b5a2ab5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { AiAssistantComponent } from '@home/pages/ai-assistant/ai-assistant.component'; +import { AiModule } from '@home/components/ai/ai.module'; +import { AiAssistantRoutingModule } from '@home/pages/ai-assistant/ai-assistant-routing.module'; + +@NgModule({ + declarations: [ + AiAssistantComponent + ], + imports: [ + CommonModule, + SharedModule, + AiModule, + AiAssistantRoutingModule + ] +}) +export class AiAssistantModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts index a6effb867d..db4a76d6bf 100644 --- a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts +++ b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts @@ -52,6 +52,7 @@ import { TrendzAnalyticsModule } from '@home/pages/trendz-analytics/trendz-analy import { TrendzSettingsModule } from '@home/pages/trendz-settings/trendz-settings.module'; import { AgentModule } from '@home/pages/agent/agent.module'; import { IotHubModule } from '@home/pages/iot-hub/iot-hub.module'; +import { AiAssistantModule } from '@home/pages/ai-assistant/ai-assistant.module'; @NgModule({ exports: [ @@ -105,7 +106,8 @@ import { IotHubModule } from '@home/pages/iot-hub/iot-hub.module'; ReportingModule, TrendzAnalyticsModule, TrendzSettingsModule, - IotHubModule + IotHubModule, + AiAssistantModule ] }) export class HomePagesModule { } 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..8f087f9deb 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -6,9 +6,15 @@ export interface ChatConfiguration { title: string; } +export interface ChatUpdate { + title?: string; + pinned?: boolean; +} + export interface ChatInfo extends ChatConfiguration { id: string; createdTime: number; + pinned?: boolean; } export interface BaseChatEvent { 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..5cc737f4cb 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -691,6 +691,7 @@ "use-system-mobile-settings": "Use system mobile settings" }, "ai-assistant": { + "ai-assistant": "AI Assistant", "configure-with-ai": "Configure with AI", "follow-up-prompt-placeholder": "Reply...", "sub-title": "I can help you set up and manage your Devices, Dashboards, Calculated Fields, Alarm Rules, and Notifications — just describe what you need, and I'll handle the rest.", @@ -741,7 +742,29 @@ }, "rename-chat-title": "Rename this chat", "export-chat": "Export chat", - "main-title": "Hello! I'm your AI Assistant" + "main-title": "Hello! I'm your AI Assistant", + "chat": "Chat", + "chats": "Chats", + "open-chats": "Open chats", + "close-chats": "Close chats", + "search-chats": "Search chats", + "chats-found": "{ count, plural, =1 {1 chat} other {# chats} }", + "no-chat-matches": "No chat matches “{{query}}”.", + "chats-show-here": "Your chats show here.", + "chat-actions": "Chat actions", + "chat-title": "Chat title", + "in-progress": "In progress", + "prompt-placeholder": "Ask about your devices, dashboards and alarms, or connect something new…", + "what-to-work-on": "What would you like to work on?", + "pinned": "Pinned", + "pin": "Pin to the top", + "unpin": "Unpin", + "double-click-to-rename": "Double-click to rename", + "auto-approve": "Auto-approve", + "auto-approve-on": "On", + "auto-approve-off": "Off", + "auto-approve-text": "Actions go ahead without waiting for your Approve.", + "auto-approve-new-chat-text": "In the new chat, actions go ahead without waiting for your Approve." }, "alarm": { "alarm": "Alarm", diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss new file mode 100644 index 0000000000..1f1370d187 --- /dev/null +++ b/ui-ngx/src/theme/ai-theme.scss @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The AI experience's design tokens (Uplink). Every AI component reads these, never a raw value: +// --ai-* the AI's colour and light, --chat-* type, space and touch, --entity-* entity types, +// --hl-* / --tb-code-* the code palette, --k-* the chat's greys and strokes. + +:root { + --tb-ink-76: rgba(0, 0, 0, 0.76); + --tb-ink-60: rgba(0, 0, 0, 0.6); + --tb-ink-54: rgba(0, 0, 0, 0.54); + --tb-ink-38: rgba(0, 0, 0, 0.38); + --tb-ink-12: rgba(0, 0, 0, 0.12); + --tb-text-secondary: rgba(0, 0, 0, 0.6); + --tb-text-muted: rgba(0, 0, 0, 0.56); + --tb-line-soft: rgba(0, 0, 0, 0.05); + --tb-surface: #ffffff; + --tb-bg: #eeeeee; + + --tb-crit-bg: rgba(209, 39, 48, 0.04); + --tb-caution-text: #955400; + --tb-ok: #198038; + --tb-ok-tint: rgba(25, 128, 56, 0.08); + --tb-ok-text: #16702f; + --tb-star: #FAE205; + + --tb-sev-critical: #D12730; + --tb-sev-major: #F35E09; + --tb-sev-minor: #B47604; + --tb-sev-warning: var(--tb-sev-minor); + --tb-sev-indeterminate: rgba(0, 0, 0, 0.54); + --tb-sev-major-text: #B04306; + --tb-sev-minor-text: #8A5A02; + --tb-sev-warning-text: #7D7003; + + --tb-soft-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); + --tb-hover-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08); + --tb-tile-radius: 10px; + + --tb-font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; + --tb-mono: "Roboto Mono", SFMono-Regular, Menlo, monospace; + + --ai-hue: 180; + --ai-light-mint: oklch(0.87 0.06 calc(var(--ai-hue) - 20)); + --ai-light-teal: oklch(0.86 0.08 calc(var(--ai-hue) - 5)); + --ai-light-aqua: oklch(0.88 0.07 calc(var(--ai-hue) + 25)); + --ai-light-lilac: oklch(0.84 0.06 295); + --ai-light-peach: oklch(0.88 0.06 45); + --ai-light-amber: oklch(0.90 0.06 80); + --ai-light-anchor: oklch(0.80 0.11 calc(var(--ai-hue) + 2)); + --ai-light-paper: oklch(0.985 0.005 calc(var(--ai-hue) + 5)); + --ai-w-teal: 90%; + --ai-w-aqua: 80%; + --ai-w-mint: 71%; + --ai-w-lilac: 55%; + --ai-w-peach: 69%; + --ai-w-amber: 55%; + --ai-light-stops: var(--ai-light-teal), var(--ai-light-aqua), var(--ai-light-lilac), var(--ai-light-peach), var(--ai-light-amber), var(--ai-light-mint), var(--ai-light-teal); + --ai-glow: conic-gradient(in oklab, var(--ai-light-stops)); + --ai-icon: + radial-gradient(80% 80% at 16% 10%, oklch(0.99 0.01 calc(var(--ai-hue) + 5) / 0.6), transparent 62%), + radial-gradient(55% 55% at 0% 100%, color-mix(in oklab, var(--ai-light-mint) 50%, transparent), transparent 70%), + radial-gradient(55% 55% at 100% 0%, color-mix(in oklab, var(--ai-light-amber) 35%, transparent), transparent 70%), + linear-gradient(135deg in oklab, oklch(0.89 0.065 calc(var(--ai-hue) - 8)) 0%, oklch(0.92 0.05 calc(var(--ai-hue) + 25)) 36%, oklch(0.89 0.045 295) 68%, oklch(0.93 0.039 50) 100%); + --ai-field-tile: + radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) var(--ai-w-teal), transparent), transparent 70%), + radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) var(--ai-w-aqua), transparent), transparent 70%), + radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) var(--ai-w-mint), transparent), transparent 70%), + radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) var(--ai-w-lilac), transparent), transparent 72%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) var(--ai-w-peach), transparent), transparent 70%), + radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) var(--ai-w-amber), transparent), transparent 70%), + var(--ai-light-paper); + --ai-field-wash: + radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) calc(var(--ai-w-teal) * .87), transparent), transparent 70%), + radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) calc(var(--ai-w-aqua) * .87), transparent), transparent 70%), + radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) calc(var(--ai-w-mint) * .87), transparent), transparent 70%), + radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) calc(var(--ai-w-lilac) * .87), transparent), transparent 72%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .87), transparent), transparent 70%), + radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .87), transparent), transparent 70%), + var(--ai-light-paper); + --ai-field-hint: + radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) calc(var(--ai-w-teal) * .48), transparent), transparent 70%), + radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) calc(var(--ai-w-aqua) * .48), transparent), transparent 70%), + radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) calc(var(--ai-w-mint) * .48), transparent), transparent 70%), + radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) calc(var(--ai-w-lilac) * .48), transparent), transparent 72%), + radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .48), transparent), transparent 70%), + radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .48), transparent), transparent 70%), + var(--ai-light-paper); + + --chat-text: 16px; + --chat-text-lh: 24px; + --chat-head: 16px; + --chat-head-lh: 24px; + --chat-line: 14px; + --chat-line-lh: 20px; + --chat-chip: 14px; + --chat-chip-lh: 18px; + --chat-meta: 12px; + --chat-meta-lh: 16px; + --chat-caption: 12px; + --chat-caption-lh: 16px; + --chat-code: 13px; + --chat-code-lh: 20px; + --chat-title: 24px; + --chat-title-lh: 32px; + --chat-turn-gap: 28px; + --chat-card-pad: 16px; + --chat-icon: 20px; + --chat-mark: 28px; + --chat-control: 32px; + --chat-tap: 0px; + --chat-text-ls: 0.25px; + --chat-key: #f6f8f8; + + --ai-teal-50: #e0f2f1; + --ai-teal-100: #b2dfdb; + --ai-teal-200: #80cbc4; + --ai-teal-300: #4db6ac; + --ai-teal-400: #26a69a; + --ai-teal-500: #00695c; + --ai-teal-600: #00897b; + --ai-teal-700: #00796b; + --ai-teal-800: #00695c; + --ai-teal-900: #004d40; + --ai-deep: #033633; + --ai-deep-hover: #23504e; + --ai-deep-pressed: #002624; + --ai-action: var(--ai-deep); + --ai-action-hover: var(--ai-deep-hover); + --ai-action-pressed: var(--ai-deep-pressed); + --ai-on-action: #ffffff; + --ai-focus: var(--ai-teal-600); + --ai-selected: var(--ai-teal-500); + --ai-selected-wash: var(--ai-teal-50); + --ai-selected-text: var(--ai-teal-900); + --ai-link: var(--ai-teal-500); + --ai-link-strong: var(--ai-teal-900); + --ai-link-line: color-mix(in srgb, var(--ai-teal-500) 35%, transparent); + --ai-focus-shadow: color-mix(in srgb, var(--ai-teal-500) 12%, transparent); + --ai-dark: #24323b; + --ai-on-dark: #e6ebee; + --ai-dark-accent: #8fe3d3; + --ai-dark-accent-hover: #a6ecdf; + --ai-dark-accent-soft: #80d6c8; + --ai-dark-accent-pale: #c4f3ea; + --ai-on-dark-accent: #0f2a26; + --ai-person: #e9f0ee; + + --entity-device-bg: #e9efff; + --entity-device-fg: #535eb8; + --entity-path-bg: #dbf5ff; + --entity-path-fg: #007592; + --entity-chain-bg: #f7eaff; + --entity-chain-fg: #814ea4; + --entity-rule-bg: #ffebdf; + --entity-rule-fg: #a34d16; + --entity-view-bg: #e0f7e5; + --entity-view-fg: #2d7b48; + --entity-people-bg: #ffe9f1; + --entity-people-fg: #a0446d; + --entity-solution-bg: #e9f1fb; + --entity-solution-fg: #586a83; + + --tb-code-bg: #1d2830; + --tb-code-fg: #dfe7ec; + --tb-code-line: rgba(255, 255, 255, 0.08); + --tb-code-head-fg: rgba(255, 255, 255, 0.7); + --hl-cmd: var(--ai-dark-accent); + --hl-flag: #9fb6c8; + --hl-str: #f2c98a; + --hl-num: #d4b4f7; + --hl-key: #9cc8f2; + --hl-com: #8a98a3; + --hl-err: #ff9d92; + --hl-fn: #d7e8a3; + --hl-bool: #f3b6d2; + --hl-lvl: #9bdda8; + --hl-mark: rgba(255, 255, 255, 0.6); + + --k-grey: var(--tb-ink-76); + --k-faint: var(--tb-text-muted); + --k-stroke: rgba(0, 0, 0, 0.1); + --k-stroke-hover: rgba(0, 0, 0, 0.2); +} + +[data-type="compact"] { + --chat-text: 14px; + --chat-text-lh: 20px; + --chat-head: 14px; + --chat-head-lh: 20px; + --chat-chip: 13px; + --chat-chip-lh: 16px; + --chat-code-lh: 18px; + --chat-title: 20px; + --chat-title-lh: 28px; +} + +[data-space="compact"] { + --chat-turn-gap: 20px; + --chat-card-pad: 12px; + --chat-icon: 18px; + --chat-mark: 24px; + --chat-control: 28px; +} + +[data-touch] { + --chat-tap: 44px; +} + +[data-ai] { + --tb-primary-50: var(--ai-teal-50); + --tb-primary-100: var(--ai-teal-100); + --tb-primary-200: var(--ai-teal-200); + --tb-primary-300: var(--ai-teal-300); + --tb-primary-400: var(--ai-teal-400); + --tb-primary-500: var(--ai-teal-500); + --tb-primary-600: var(--ai-teal-600); + --tb-primary-700: var(--ai-teal-700); + --tb-primary-800: var(--ai-teal-800); + --tb-primary-900: var(--ai-teal-900); + --tb-primary-contrast-500: #ffffff; +} + +@property --ai-h { + syntax: ''; + inherits: true; + initial-value: 172; +} + +.tb-ai-mark { + --m: 28px; + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: var(--m); + height: var(--m); + border-radius: 38%; + background: var(--ai-icon); + background-size: 240% 240%; + animation: tb-ai-icon-flow 8s ease-in-out infinite alternate, tb-ai-mark-hue 6s ease-in-out infinite alternate; + + .mat-icon { + font-size: calc(var(--m) * .57); + width: calc(var(--m) * .57); + height: calc(var(--m) * .57); + line-height: 1; + color: oklch(0.32 0.07 var(--ai-h)) !important; + } + + &.m24 { --m: 24px; } + &.m32 { --m: 32px; } + &.m44 { --m: 44px; } + &.m64 { --m: 64px; } + + &.m44, &.m64 { + box-shadow: 0 1px 2px rgb(16 24 40 / 0.06), 0 8px 24px color-mix(in oklab, var(--ai-light-teal) 26%, transparent); + } + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes tb-ai-icon-flow { + 0% { background-position: 0% 0%; } + 50% { background-position: 100% 60%; } + 100% { background-position: 40% 100%; } +} + +@keyframes tb-ai-mark-hue { + from { --ai-h: calc(var(--ai-hue) - 8); } + to { --ai-h: calc(var(--ai-hue) + 120); } +} + +.tb-ai-status-mark { + flex: none; + width: 12px; + height: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + + &::before { + content: ''; + display: block; + } + + &.running::before { + width: 9px; + height: 9px; + box-sizing: border-box; + border-radius: 50%; + border: 2px solid var(--tb-ink-38); + border-top-color: transparent; + animation: tb-ai-status-turn .9s linear infinite; + } + + @media (prefers-reduced-motion: reduce) { + &.running::before { + animation: none; + border-top-color: var(--tb-ink-38); + } + } +} + +@keyframes tb-ai-status-turn { + to { transform: rotate(360deg); } +} + +.mat-mdc-menu-panel.tb-ai-chat-menu { + min-width: 200px; + max-width: 300px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06), 0 4px 12px rgba(16, 24, 40, 0.10), 0 12px 32px rgba(16, 24, 40, 0.10); + + .mat-mdc-menu-content { + padding: 6px; + } + + .mat-mdc-menu-item { + min-height: 34px; + height: 34px; + padding: 0 10px; + border-radius: 8px; + gap: 10px; + + .mat-mdc-menu-item-text { + font: 400 13.5px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); + } + + .mat-icon { + margin-right: 0; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + color: var(--tb-ink-60); + } + + &:hover:not([disabled]), &.cdk-program-focused, &.cdk-keyboard-focused { + background: rgba(0, 0, 0, 0.05); + } + + &.danger { + position: relative; + margin-top: 7px; + overflow: visible; + + &::before { + content: ''; + display: block; + position: absolute; + left: 4px; + right: 4px; + top: -4px; + bottom: auto; + height: 1px; + border: 0; + border-radius: 0; + background: rgba(0, 0, 0, 0.08); + } + + .mat-mdc-menu-item-text, .mat-icon { + color: var(--tb-crit); + } + + &:hover:not([disabled]) { + background: var(--tb-crit-tint); + } + } + } +} + +.mat-mdc-tooltip.tb-ai-cursor-tooltip { + translate: -12px 30px; +} diff --git a/ui-ngx/src/theme/app-theme.scss b/ui-ngx/src/theme/app-theme.scss index 682d7c1cf9..4b2231b2ce 100644 --- a/ui-ngx/src/theme/app-theme.scss +++ b/ui-ngx/src/theme/app-theme.scss @@ -5,6 +5,7 @@ @use '@angular/material/core/tokens/m2-utils'; @import './datepicker-theme'; @import './theme-constants'; +@import './ai-theme'; @include mat.elevation-classes(); @include mat.app-background(); From 9799e80ac981802c98442a711a4cf192803bcadf Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Wed, 4 Nov 2026 16:25:33 +0200 Subject: [PATCH 002/183] feat: AI chat messages show the time they were said, and each answer has a copy button shown on hover and always on the latest answer --- .../ai/ai-assistant-panel.component.ts | 6 +- .../ai/ai-chat-messages.component.html | 21 +++++- .../ai/ai-chat-messages.component.scss | 69 +++++++++++++++++++ .../ai/ai-chat-messages.component.ts | 32 ++++++++- .../home/components/ai/ai-chat.component.ts | 6 +- .../shared/models/solution-creator.models.ts | 1 + .../assets/locale/locale.constant-en_US.json | 2 + 7 files changed, 129 insertions(+), 8 deletions(-) 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 a9a7b8e259..75cc5ceca6 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 @@ -252,8 +252,8 @@ export class AiAssistantPanelComponent implements OnInit { sendMsgFromUser(prompt: AiPromptMessage): void { const userMessage: ChatMessage = prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources} - : {from: 'USER', content: prompt.message}; + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} + : {from: 'USER', content: prompt.message, time: Date.now()}; this.messages.update(list => [...list, userMessage]); this.sendMessage(prompt).subscribe({ error: (err) => { @@ -505,7 +505,7 @@ export class AiAssistantPanelComponent implements OnInit { private handleChatEvent(chatMsg: ChatEvent): Observable { switch (chatMsg.event) { case 'assistantMessage': - this.messages.update(list => [...list, {from: 'AI', content: chatMsg.data.message}]); + this.messages.update(list => [...list, {from: 'AI', content: chatMsg.data.message, time: Date.now()}]); return of(chatMsg); case 'toolExecutionRequested': return this.handleToolApproval(chatMsg); 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 5523b3295e..8de944f534 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 @@ -13,6 +13,11 @@ @if (msg.content) {
{{ msg.content }}
} + @if (msg.time) { +
+ +
+ } } @else {
@@ -29,10 +34,24 @@ {{ msg.content }}
} @else { -
+
+
+ @if (msg.time) { + + } + + + +
}
} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 43d8af9003..99132af595 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -45,6 +45,75 @@ } } + .msg-foot { + display: flex; + align-items: center; + gap: 2px; + min-height: 24px; + margin-top: -2px; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); + font-variant-numeric: tabular-nums; + + &.agent-foot { + margin-top: 4px; + padding-left: calc(var(--chat-mark) + 10px); + } + + time { + margin-right: 6px; + } + } + + .foot-tools { + display: inline-flex; + align-items: center; + gap: 2px; + opacity: 0; + transition: opacity .12s ease; + + &.show { + opacity: 1; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } + } + + .ai:hover .foot-tools, .ai:focus-within .foot-tools { + opacity: 1; + } + + .foot-tool { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.done { + color: var(--tb-ok); + } + } + .agent { display: flex; align-items: flex-start; 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 e837fc06b4..5c21698ca9 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 @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; +import { ClipboardService } from 'ngx-clipboard'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; @Component({ @@ -25,10 +26,27 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { waitApproval = false; private static readonly PIN_TO_BOTTOM_MS = 1500; + private static readonly COPIED_MS = 1200; private releaseBottom: () => void; - constructor(private elementRef: ElementRef) {} + lastAnswerIndex = -1; + + copiedIndex = -1; + + private copiedTimeout: ReturnType; + + constructor(private elementRef: ElementRef, + private clipboard: ClipboardService) {} + + copyAnswer(answer: HTMLElement, index: number): void { + const text = (answer.querySelector('.agent-body') ?? answer).innerText.trim(); + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => this.copiedIndex = -1, AiChatMessagesComponent.COPIED_MS); + } + } getApprovalData(msg: ApprovalChatMessage): ToolExecutionRequested { return msg.data; @@ -45,6 +63,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } } if (changes.messages) { + this.lastAnswerIndex = this.findLastAnswerIndex(); if (changes.messages.firstChange) { if (this.initialScroll === 'bottom') { this.pinToBottom(); @@ -87,7 +106,18 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { this.approvalAction.emit($event); } + private findLastAnswerIndex(): number { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'AI' && message.status !== 'INCOMPLETE') { + return i; + } + } + return -1; + } + ngOnDestroy(): void { + clearTimeout(this.copiedTimeout); this.releaseBottom?.(); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 2fffca8bee..13883e195c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -250,8 +250,8 @@ export class AiChatComponent implements OnInit, OnDestroy { sendMsgFromUser(prompt: AiPromptMessage): void { const userMessage: ChatMessage = prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources} - : {from: 'USER', content: prompt.message}; + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} + : {from: 'USER', content: prompt.message, time: Date.now()}; this.messages.update(list => [...list, userMessage]); this.sendMessage(prompt).subscribe({ error: err => { @@ -370,7 +370,7 @@ export class AiChatComponent implements OnInit, OnDestroy { private handleChatEvent(event: ChatEvent): Observable { switch (event.event) { case 'assistantMessage': - this.messages.update(list => [...list, {from: 'AI', content: event.data.message}]); + this.messages.update(list => [...list, {from: 'AI', content: event.data.message, time: Date.now()}]); break; case 'toolExecutionRequested': this.handleToolApproval(event); diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 5257dd27fb..77be22238b 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -179,6 +179,7 @@ export interface GeneralChatMessage { content: string; status?: 'INCOMPLETE'; resources?: AiResourceInfo[]; + time?: number; } export interface ApprovalChatMessage { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 5cc737f4cb..258de6baa0 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -760,6 +760,8 @@ "pin": "Pin to the top", "unpin": "Unpin", "double-click-to-rename": "Double-click to rename", + "copy-answer": "Copy the answer", + "copied": "Copied", "auto-approve": "Auto-approve", "auto-approve-on": "On", "auto-approve-off": "Off", From bd65304a668bc02c69a9af4c7bcb6f7eb3393e07 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Wed, 4 Nov 2026 18:15:12 +0200 Subject: [PATCH 003/183] feat: AI chat: deny an approval with what should be different (from the card or the composer), status marks for chats that run or need the user, and Stop / Esc for a running reply --- .../server/controller/AiChatController.java | 9 ++ .../server/service/ai/chat/AiChatService.java | 2 + .../service/ai/chat/DefaultAiChatService.java | 6 ++ .../ai/chat/DefaultAiChatServiceTest.java | 16 ++++ ui-ngx/src/app/core/http/ai-chat.service.ts | 4 + .../src/app/core/services/ai-chats.service.ts | 45 ++++++++-- .../ai/ai-approval-card.component.html | 7 ++ .../ai/ai-approval-card.component.scss | 24 ++++++ .../ai/ai-approval-card.component.ts | 33 ++++++- .../ai/ai-chat-messages.component.html | 6 ++ .../ai/ai-chat-messages.component.ts | 5 ++ .../home/components/ai/ai-chat.component.html | 12 ++- .../home/components/ai/ai-chat.component.scss | 24 +++++- .../home/components/ai/ai-chat.component.ts | 86 +++++++++++++++++-- .../ai/ai-prompt-input.component.html | 40 ++++++--- .../ai/ai-prompt-input.component.scss | 14 +++ .../ai/ai-prompt-input.component.ts | 21 +++++ .../ai-assistant/ai-assistant.component.html | 4 +- .../ai-assistant/ai-assistant.component.ts | 16 +++- .../src/app/shared/models/ai-chat.models.ts | 14 ++- .../assets/locale/locale.constant-en_US.json | 8 ++ ui-ngx/src/theme/ai-theme.scss | 15 ++++ 22 files changed, 380 insertions(+), 31 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java index bbd9366776..40e7cfabcb 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java @@ -65,6 +65,15 @@ class AiChatController extends BaseController { aiChatService.updateChat(chatId, request, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/{chatId}/stop") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void stopChat(@PathVariable UUID chatId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + aiChatService.stopChat(chatId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping public JsonNode listChats() throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java index 2eae20227a..b5d698af60 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java @@ -15,6 +15,8 @@ public interface AiChatService { void updateChat(UUID chatId, JsonNode request, SecurityUser user); + void stopChat(UUID chatId, SecurityUser user); + JsonNode listChats(SecurityUser user); JsonNode getChatMessages(UUID chatId, SecurityUser user); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java index 1b15fc8045..52bf9de418 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java @@ -56,6 +56,12 @@ class DefaultAiChatService implements AiChatService { new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false); } + @Override + public void stopChat(UUID chatId, SecurityUser user) { + tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false); + } + @Override public void deleteChat(UUID chatId, SecurityUser user) { tbAiService.process(tokenProvider -> operations.execute( diff --git a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java index a5606a95bf..f97b8c79bb 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java @@ -155,6 +155,22 @@ class DefaultAiChatServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopChatCalled() { + // GIVEN + UUID chatId = UUID.randomUUID(); + given(tbAiService.process(any(), same(user), eq(false))).willReturn(null); + + // WHEN + service.stopChat(chatId, user); + + // THEN + assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type()) + && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); + then(tbAiService).shouldHaveNoMoreInteractions(); + } + @Test void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() { // GIVEN diff --git a/ui-ngx/src/app/core/http/ai-chat.service.ts b/ui-ngx/src/app/core/http/ai-chat.service.ts index 3044f6a0e8..bd70582ce2 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -62,6 +62,10 @@ export class AiChatService { * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the * live ones. Completes with no events when nothing is running. */ + public stopChat(chatId: string, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/chats/${chatId}/stop`, null, defaultHttpOptionsFromConfig(config)); + } + public resumeChat(chatId: string, config?: RequestConfig): Observable { return this.streamEvents(`/api/ai/chats/${chatId}/resume`, null, config); } diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts index 192dfab1aa..7d9a060f5c 100644 --- a/ui-ngx/src/app/core/services/ai-chats.service.ts +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { inject, Injectable, signal } from '@angular/core'; +import { inject, Injectable, signal, untracked, WritableSignal } from '@angular/core'; import { Observable, of } from 'rxjs'; import { map, switchMap, tap } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; import { AiChatService } from '@core/http/ai-chat.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { DialogService } from '@core/services/dialog.service'; -import { ChatInfo } from '@shared/models/ai-chat.models'; +import { ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; @Injectable({ providedIn: 'root' }) export class AiChatsService { @@ -26,6 +26,37 @@ export class AiChatsService { private _replying = signal>(new Set()); readonly replying = this._replying.asReadonly(); + private _waiting = signal>(new Set()); + + private _open = signal>(new Set()); + + levelOf(chat: ChatInfo): ChatLevel | null { + if (this._waiting().has(chat.id)) { + return 'needs'; + } + if (this._replying().has(chat.id)) { + return 'running'; + } + if (this._open().has(chat.id)) { + return null; + } + return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'RUNNING' ? 'running' : null; + } + + setWaiting(chatId: string | undefined, waiting: boolean): void { + this.toggle(this._waiting, chatId, waiting); + } + + setOpen(chatId: string | undefined, open: boolean): void { + this.toggle(this._open, chatId, open); + } + + refresh(): Observable { + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + tap(chats => this._chats.set(chats)) + ); + } + load(): Observable { return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( tap({ @@ -93,12 +124,16 @@ export class AiChatsService { } setReplying(chatId: string | undefined, replying: boolean): void { - if (!chatId) { + this.toggle(this._replying, chatId, replying); + } + + private toggle(target: WritableSignal>, chatId: string | undefined, on: boolean): void { + if (!chatId || untracked(target).has(chatId) === on) { return; } - this._replying.update(set => { + target.update(set => { const next = new Set(set); - if (replying) { + if (on) { next.add(chatId); } else { next.delete(chatId); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index ce8881931c..e781c64d4f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -18,6 +18,13 @@ {{ data.approveLabel ?? ('ai-assistant.approve' | translate) }} + @if (denying) { + + } + @if (canStop) { + + } @else { + + }
@@ -89,6 +100,13 @@
+ +
+ {{ 'ai-assistant.stop' | translate }} + Esc +
+
+
{{ 'ai-assistant.send' | 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 da26d7dccd..2729daa8f2 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 @@ -200,6 +200,20 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= display: inline-flex; } + .composer-stop { + &:disabled { + opacity: .6; + cursor: default; + } + + .stop-glyph { + width: 10px; + height: 10px; + border-radius: 2px; + background: var(--ai-on-action); + } + } + .composer-send { position: relative; display: inline-flex; 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 884a95088d..57d2c852a5 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 @@ -83,6 +83,22 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr @Output() autoApproveChange = new EventEmitter(); + @Input() stoppable = false; + + @Input() stopping = false; + + @Output() stopped = new EventEmitter(); + + get canStop(): boolean { + return this.loading && this.stoppable; + } + + stop(): void { + if (this.canStop && !this.stopping) { + this.stopped.emit(); + } + } + @ViewChild('textarea') textarea!: ElementRef; @ViewChild('fileInput') fileInput!: ElementRef; @@ -158,6 +174,11 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } onKeydown(event: KeyboardEvent): void { + if (event.key === 'Escape' && this.canStop) { + event.preventDefault(); + this.stop(); + return; + } if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) { event.preventDefault(); this.send(); diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html index eab5fd617f..57e7d0249f 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html @@ -58,8 +58,8 @@ {{ chat.title }} - @if (aiChats.replying().has(chat.id)) { - + @if (aiChats.levelOf(chat); as level) { + }
} + } @else if (msg.from === 'ACTION') { +
+ +
} @else {
@if (msg.from === 'APPROVAL') { @@ -63,10 +67,12 @@ } } } -@if (loading && !waitApproval) { +@if (loading && !waitApproval && !actionRunning) {
@if (loadingLongTime) { + } @else if (work) { + } @else {
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 99132af595..111370a1c0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -148,9 +148,18 @@ } } + .ai.action + .ai.action { + margin-top: calc(6px - var(--chat-turn-gap)); + } + .generating { gap: 10px; + .work { + flex: 1; + min-width: 0; + } + .tb-ai-mark { --m: var(--chat-mark); } 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 68cdfd9d53..60b40f1ad5 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 @@ -4,6 +4,7 @@ import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Outpu import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; import { ClipboardService } from 'ngx-clipboard'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { AiWorkState } from '@home/components/ai/ai-action.models'; @Component({ selector: 'tb-ai-chat-messages', @@ -22,11 +23,14 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() scrollContainer: HTMLElement; @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; @Input() denyReasons: Record = {}; + @Input() work: AiWorkState | undefined; @Output() approvalAction = new EventEmitter(); @Output() resourceError = new EventEmitter(); waitApproval = false; + actionRunning = false; + private static readonly PIN_TO_BOTTOM_MS = 1500; private static readonly COPIED_MS = 1200; @@ -70,6 +74,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } if (changes.messages) { this.lastAnswerIndex = this.findLastAnswerIndex(); + this.actionRunning = this.messages.some(message => message.from === 'ACTION' && message.data.status === 'RUNNING'); if (changes.messages.firstChange) { if (this.initialScroll === 'bottom') { this.pinToBottom(); @@ -97,6 +102,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } else if (wasNearBottom) { setTimeout(() => this.scrollToLastAiMessage(), 0); } + } else if (lastMsg?.from === 'ACTION') { + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('smooth'), 0); + } } else if (lastMsg?.from === 'APPROVAL') { if (prevLastMsg?.from === 'USER') { setTimeout(() => this.scrollToLastUserMessage(), 0); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 55479c939f..9f6e31d7e6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -59,6 +59,7 @@ [scrollContainer]="chatArea" initialScroll="bottom" [denyReasons]="denyReasons()" + [work]="work()" (approvalAction)="onApprovalAction($event)"> } @else if (!chatId()) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 10f6c98f53..3e118c5a06 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -36,9 +36,13 @@ import { ApprovalResult, ChatEvent, SendChatMessageRequest, + AiAction, ToolExecutionRequestedEvent, - ToolExecutionResult + ToolExecutionResult, + ToolFinished, + ToolStarted } from '@shared/models/ai-chat.models'; +import { AiWorkMoment, AiWorkState, isHiddenAiAction } from '@home/components/ai/ai-action.models'; import { EntityId } from '@shared/models/id/entity-id'; import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; @@ -106,6 +110,8 @@ export class AiChatComponent implements OnInit, OnDestroy { stopping = signal(false); + work = signal(undefined); + private answeredApprovals = signal>(new Set()); waitingApproval = computed(() => { @@ -294,6 +300,7 @@ export class AiChatComponent implements OnInit, OnDestroy { this.panelService.setAutoApprove(chatId, true); } this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + this.setWork(event.approved ? 'applying-change' : event.reason ? 'reading-what-to-change' : 'going-through-results'); if (event.reason) { this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); } @@ -446,6 +453,12 @@ export class AiChatComponent implements OnInit, OnDestroy { this.affectedEntities.push(...event.data.affectedEntities); } break; + case 'toolStarted': + this.startAction(event.data); + break; + case 'toolFinished': + this.finishAction(event.data); + break; case 'turnStopped': this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'INCOMPLETE', time: Date.now()}]); break; @@ -462,6 +475,47 @@ export class AiChatComponent implements OnInit, OnDestroy { return of(event); } + private startAction(started: ToolStarted): void { + if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId)) { + return; + } + const action: AiAction = { + executionId: started.executionId, + tool: started.tool, + arguments: started.arguments, + status: 'RUNNING', + startedAt: Date.now() + }; + this.messages.update(list => [...list, {from: 'ACTION', data: action}]); + } + + private finishAction(finished: ToolFinished): void { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result}} + : message)); + if (!this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.setWork('going-through-results', true); + } + } + + private isApprovalExecution(executionId: string): boolean { + return this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === executionId); + } + + private stopRunningActions(): void { + if (this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.status === 'RUNNING' + ? {from: 'ACTION', data: {...message.data, status: 'STOPPED', durationMs: Date.now() - message.data.startedAt}} + : message)); + } + } + + private setWork(moment: AiWorkMoment, restart = false): void { + if (restart || this.work()?.moment !== moment) { + this.work.set({moment, since: Date.now()}); + } + } + private handleToolApproval(event: ToolExecutionRequestedEvent): void { if (event.data.needsApproval) { this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]); @@ -496,6 +550,7 @@ export class AiChatComponent implements OnInit, OnDestroy { private startLoading(): void { this.loading.set(true); + this.setWork('reading-request'); this.chats.setReplying(this.replyingChatId, false); this.replyingChatId = this.chatId(); this.chats.setReplying(this.replyingChatId, true); @@ -507,6 +562,8 @@ export class AiChatComponent implements OnInit, OnDestroy { } this.loading.set(false); this.stopping.set(false); + this.work.set(undefined); + this.stopRunningActions(); if (this.affectedEntities.length) { this.panelService.emitUpdatedData(this.affectedEntities); this.affectedEntities = []; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss new file mode 100644 index 0000000000..af3c53f33a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + color: var(--ai-teal-500); + + &[data-kind="listen"] { + color: var(--tb-caution); + } + + &[data-kind="stop"] { + color: var(--tb-ink-38); + } +} + +.cell { + display: grid; + grid-template-columns: repeat(2, 3px); + grid-template-rows: repeat(3, 3px); + gap: 2px 3px; + + i { + width: 3px; + height: 3px; + border-radius: 50%; + background: currentColor; + visibility: hidden; + + &.on { + visibility: visible; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts new file mode 100644 index 0000000000..1d72167969 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, Input, NgZone, OnDestroy, OnInit } from '@angular/core'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; + +const FRAME_MS = 80; +const DOT_BITS = [0x01, 0x08, 0x02, 0x10, 0x04, 0x20]; + +const FRAMES: Record = { + think: [...'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'].map(glyph => glyph.charCodeAt(0) - 0x2800), + listen: [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x3f, 0x3e, 0x3c, 0x38, 0x30, 0x20, 0x00], + gen: [0x01, 0x08, 0x10, 0x20, 0x04, 0x02].map(bit => 0x3f & ~bit), + install: [0x09, 0x12, 0x24, 0x2d, 0x36, 0x3f, 0x3f, 0x3f, 0x00], + stop: [0x12] +}; + +const spinners = new Set(); +let tick = 0; +let timer: ReturnType | undefined; + +function startTimer(zone: NgZone): void { + if (timer || matchMedia('(prefers-reduced-motion: reduce)').matches) { + return; + } + zone.runOutsideAngular(() => { + timer = setInterval(() => { + tick++; + spinners.forEach(spinner => spinner.draw()); + }, FRAME_MS); + }); +} + +@Component({ + selector: 'tb-ai-spin', + template: '', + styleUrls: ['./ai-spin.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'aria-hidden': 'true', + '[attr.data-kind]': 'kind' + } +}) +export class AiSpinComponent implements OnInit, OnDestroy { + + private kindValue: AiSpinKind = 'think'; + + @Input() + set kind(kind: AiSpinKind) { + this.kindValue = kind ?? 'think'; + this.draw(); + } + + get kind(): AiSpinKind { + return this.kindValue; + } + + private host = inject>(ElementRef); + private zone = inject(NgZone); + + ngOnInit(): void { + spinners.add(this); + this.draw(); + startTimer(this.zone); + } + + ngOnDestroy(): void { + spinners.delete(this); + if (!spinners.size && timer) { + clearInterval(timer); + timer = undefined; + } + } + + draw(): void { + const frames = FRAMES[this.kindValue]; + const bits = frames[tick % frames.length]; + const dots = this.host.nativeElement.querySelectorAll('i'); + dots.forEach((dot, index) => dot.classList.toggle('on', !!(bits & DOT_BITS[index]))); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss new file mode 100644 index 0000000000..77fc610d16 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); + + tb-ai-spin { + margin-block: calc((var(--chat-line-lh) - 16px) / 2); + } +} + +.say { + min-width: 0; +} + +.clock { + margin-left: auto; + padding-left: 12px; + font-family: var(--tb-mono); + font-size: var(--chat-meta); + color: var(--k-faint); + white-space: nowrap; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts new file mode 100644 index 0000000000..f2757372e8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, NgZone, OnInit, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSpinKind, aiWorkClock } from '@home/components/ai/ai-action.models'; + +const CLOCK_AFTER_MS = 10_000; +const STILL_AFTER_MS = 30_000; + +@Component({ + selector: 'tb-ai-work-line', + template: ` + + {{ say() }} + @if (clock(); as time) { + {{ time }} + } + `, + styleUrls: ['./ai-work-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'role': 'status', + '[attr.aria-label]': 'words()' + } +}) +export class AiWorkLineComponent implements OnInit { + + words = input.required(); + + kind = input('think'); + + since = input(Date.now()); + + private now = signal(Date.now()); + + private elapsed = computed(() => Math.max(0, this.now() - this.since())); + + say = computed(() => { + const words = this.words(); + if (this.elapsed() < STILL_AFTER_MS || !words) { + return words; + } + return this.translate.instant('ai-assistant.work.still', {words: words.charAt(0).toLocaleLowerCase() + words.slice(1)}); + }); + + clock = computed(() => this.elapsed() >= CLOCK_AFTER_MS ? aiWorkClock(this.elapsed()) : undefined); + + private translate = inject(TranslateService); + private zone = inject(NgZone); + private destroyRef = inject(DestroyRef); + + ngOnInit(): void { + const timer = this.zone.runOutsideAngular(() => setInterval(() => this.zone.run(() => this.now.set(Date.now())), 1000)); + this.destroyRef.onDestroy(() => clearInterval(timer)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index e8119fb9c4..af5d695777 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -16,6 +16,9 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; +import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component'; +import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; @NgModule({ declarations: [ @@ -31,7 +34,10 @@ import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; AiNoTelemetryModalComponent, AiAttachmentsComponent, AiAttachmentPreviewDialogComponent, - AiTipDirective + AiTipDirective, + AiSpinComponent, + AiWorkLineComponent, + AiActionLineComponent ], imports: [ CommonModule, 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 0c3bdcea41..0f3f650b9f 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -107,6 +107,39 @@ export interface TurnStoppedEvent extends BaseChatEvent { data: Record; } +export interface ToolStarted extends BaseChatToolEventData { + tool: string; + arguments?: unknown; +} + +export interface ToolStartedEvent extends BaseChatEvent { + event: 'toolStarted'; + data: ToolStarted; +} + +export interface ToolFinished extends BaseChatToolEventData { + status: 'SUCCESS' | 'FAILURE'; + durationMs: number; + result?: string; +} + +export interface ToolFinishedEvent extends BaseChatEvent { + event: 'toolFinished'; + data: ToolFinished; +} + +export type AiActionStatus = 'RUNNING' | 'SUCCESS' | 'FAILURE' | 'STOPPED'; + +export interface AiAction { + executionId: string; + tool: string; + arguments?: unknown; + status: AiActionStatus; + startedAt: number; + durationMs?: number; + result?: string; +} + export interface ApprovalResult { executionId: string; approved: boolean; @@ -121,7 +154,7 @@ export enum ToolApprovalResult { } export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent - | TurnResumedEvent | TurnStoppedEvent; + | TurnResumedEvent | TurnStoppedEvent | ToolStartedEvent | ToolFinishedEvent; export enum AiAssistantViewType { DASHBOARD = 'DASHBOARD', diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 77be22238b..023def6d0b 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -7,7 +7,7 @@ import { EntityId } from '@shared/models/id/entity-id'; import { BaseData } from '@shared/models/base-data'; import { CalculatedFieldType } from '@shared/models/calculated-field.models'; import { AlarmSeverity } from '@shared/models/alarm.models'; -import { ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AiAction, ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; export interface SolutionInfo { id: string; @@ -172,7 +172,7 @@ export interface SolutionStepState { skipInterviewAllowed?: boolean; } -export type ChatMessage = GeneralChatMessage | ApprovalChatMessage; +export type ChatMessage = GeneralChatMessage | ApprovalChatMessage | ActionChatMessage; export interface GeneralChatMessage { from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE'; @@ -182,6 +182,11 @@ export interface GeneralChatMessage { time?: number; } +export interface ActionChatMessage { + from: 'ACTION'; + data: AiAction; +} + export interface ApprovalChatMessage { from: 'APPROVAL'; data: ToolExecutionRequested; 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 213165ffc6..4160d5f34b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -731,6 +731,252 @@ "attachment-larger-than": "Larger than {{size}}", "attachment-svg-failed": "This SVG can't be converted to an image", "attachment-over-limit": "More than {{count}} files", + "action": { + "search-devices": { + "run": "Looking up devices", + "done": "Looked up devices" + }, + "search-assets": { + "run": "Looking up assets", + "done": "Looked up assets" + }, + "search-dashboards": { + "run": "Looking up dashboards", + "done": "Looked up dashboards" + }, + "search-customers": { + "run": "Looking up customers", + "done": "Looked up customers" + }, + "search-users": { + "run": "Looking up users", + "done": "Looked up users" + }, + "search-tenant": { + "run": "Searching the tenant", + "done": "Searched the tenant" + }, + "read-entity": { + "run": "Reading the record", + "done": "Read the record" + }, + "read-latest-values": { + "run": "Reading the latest values", + "done": "Read the latest values" + }, + "read-history": { + "run": "Reading the history", + "done": "Read the history" + }, + "read-telemetry-keys": { + "run": "Reading the telemetry keys", + "done": "Read the telemetry keys" + }, + "read-attributes": { + "run": "Reading attributes", + "done": "Read attributes" + }, + "save-attributes": { + "run": "Updating the attributes", + "done": "Updated the attributes" + }, + "delete-attributes": { + "run": "Deleting the attributes", + "done": "Deleted the attributes" + }, + "read-relations": { + "run": "Following relations", + "done": "Followed relations" + }, + "read-credentials": { + "run": "Reading the device credentials", + "done": "Read the device credentials" + }, + "save-device": { + "run": "Saving the device", + "done": "Saved the device" + }, + "save-calculated-field": { + "run": "Saving the calculated field", + "done": "Saved the calculated field" + }, + "recalculate-history": { + "run": "Recalculating history", + "done": "Recalculated history" + }, + "save-alarm-rule": { + "run": "Saving the alarm rule", + "done": "Saved the alarm rule" + }, + "create-dashboard": { + "run": "Creating the dashboard", + "done": "Created the dashboard" + }, + "update-dashboard": { + "run": "Updating the dashboard", + "done": "Updated the dashboard" + }, + "add-dashboard-state": { + "run": "Adding a dashboard state", + "done": "Added a dashboard state" + }, + "update-dashboard-state": { + "run": "Updating the dashboard state", + "done": "Updated the dashboard state" + }, + "add-entity-alias": { + "run": "Adding an entity alias", + "done": "Added an entity alias" + }, + "update-entity-alias": { + "run": "Updating the entity alias", + "done": "Updated the entity alias" + }, + "read-entity-alias": { + "run": "Reading the entity alias", + "done": "Read the entity alias" + }, + "add-dashboard-filter": { + "run": "Adding a dashboard filter", + "done": "Added a dashboard filter" + }, + "update-dashboard-filter": { + "run": "Updating the dashboard filter", + "done": "Updated the dashboard filter" + }, + "read-dashboard-filter": { + "run": "Reading the dashboard filter", + "done": "Read the dashboard filter" + }, + "read-dashboard": { + "run": "Reading the dashboard", + "done": "Read the dashboard" + }, + "add-widgets": { + "run": "Adding widgets", + "done": "Added widgets" + }, + "update-widget": { + "run": "Updating the widget", + "done": "Updated the widget" + }, + "place-widgets": { + "run": "Placing the widgets", + "done": "Placed the widgets" + }, + "read-widget": { + "run": "Reading the widget", + "done": "Read the widget" + }, + "lay-out-dashboard": { + "run": "Laying out the dashboard", + "done": "Laid out the dashboard" + }, + "read-dashboard-page": { + "run": "Reading the dashboard page", + "done": "Read the dashboard page" + }, + "save-notification-target": { + "run": "Saving the notification recipients", + "done": "Saved the notification recipients" + }, + "save-notification-template": { + "run": "Saving the notification template", + "done": "Saved the notification template" + }, + "save-notification-rule": { + "run": "Saving the notification rule", + "done": "Saved the notification rule" + }, + "search-iot-hub": { + "run": "Searching IoT Hub", + "done": "Searched IoT Hub" + }, + "read-connection-settings": { + "run": "Looking up the connection settings", + "done": "Looked up the connection settings" + }, + "research-device": { + "run": "Researching the device", + "done": "Researched the device" + }, + "search-web": { + "run": "Searching the web", + "done": "Searched the web" + }, + "read-page": { + "run": "Reading the page", + "done": "Read the page" + }, + "read-site": { + "run": "Reading {{site}}", + "done": "Read {{site}}" + }, + "delete-calculated-field": { + "run": "Deleting the calculated field", + "done": "Deleted the calculated field" + }, + "delete-alarm-rule": { + "run": "Deleting the alarm rule", + "done": "Deleted the alarm rule" + }, + "delete-notification-rule": { + "run": "Deleting the notification rule", + "done": "Deleted the notification rule" + }, + "delete-notification-target": { + "run": "Deleting the notification recipients", + "done": "Deleted the notification recipients" + }, + "delete-notification-template": { + "run": "Deleting the notification template", + "done": "Deleted the notification template" + }, + "delete-dashboard": { + "run": "Deleting the dashboard", + "done": "Deleted the dashboard" + }, + "delete-widget": { + "run": "Deleting the widget", + "done": "Deleted the widget" + }, + "delete-dashboard-state": { + "run": "Deleting the dashboard state", + "done": "Deleted the dashboard state" + }, + "delete-entity-alias": { + "run": "Deleting the entity alias", + "done": "Deleted the entity alias" + }, + "delete-dashboard-filter": { + "run": "Deleting the dashboard filter", + "done": "Deleted the dashboard filter" + }, + "delete-device": { + "run": "Deleting the device", + "done": "Deleted the device" + }, + "delete-other": { + "run": "Deleting", + "done": "Deleted" + }, + "other": { + "run": "Working on a step", + "done": "Finished a step" + }, + "failed": "Failed while {{words}}", + "details": "Details", + "request": "Request", + "result": "Result" + }, + "work": { + "reading-request": "Reading the request", + "going-through-results": "Going through the results", + "applying-change": "Applying the change", + "reading-what-to-change": "Reading what to change", + "still": "Still {{words}}", + "stopped": "Stopped while {{words}}" + }, "file-kind": { "image": "Image", "pdf": "PDF", From f5057cf5687a0069d433507eae425403903b9fd5 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 15:13:17 +0200 Subject: [PATCH 005/183] feat: a run ends with a summary of what it made or changed: one linked row per entity from the turn's approvals and action lines, under the agent's last message --- .../ai/ai-chat-messages.component.html | 6 + .../ai/ai-chat-messages.component.scss | 8 ++ .../ai/ai-chat-messages.component.ts | 46 +++++++ .../home/components/ai/ai-chat.component.ts | 6 +- .../ai/ai-run-summary.component.html | 31 +++++ .../ai/ai-run-summary.component.scss | 84 ++++++++++++ .../components/ai/ai-run-summary.component.ts | 125 ++++++++++++++++++ .../modules/home/components/ai/ai.module.ts | 4 +- .../src/app/shared/models/ai-chat.models.ts | 2 + .../assets/locale/locale.constant-en_US.json | 5 + 10 files changed, 315 insertions(+), 2 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.html create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts 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 391d844d64..1ee961e241 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 @@ -39,11 +39,17 @@ warning_amber {{ msg.content }}
+ @if (summaries[$index]; as entities) { + + } } @else {
+ @if (summaries[$index]; as entities) { + + }
@if (msg.time) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 111370a1c0..8c840f385e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -148,6 +148,14 @@ } } + .ai .summary { + margin-left: calc(var(--chat-mark) + 10px); + } + + .ai .incomplete + .summary { + margin-left: 0; + } + .ai.action + .ai.action { margin-top: calc(6px - var(--chat-turn-gap)); } 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 60b40f1ad5..d732a044ca 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 @@ -5,6 +5,7 @@ import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creato import { ClipboardService } from 'ngx-clipboard'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; import { AiWorkState } from '@home/components/ai/ai-action.models'; +import { EntityId } from '@shared/models/id/entity-id'; @Component({ selector: 'tb-ai-chat-messages', @@ -31,6 +32,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { actionRunning = false; + summaries: Record = {}; + private static readonly PIN_TO_BOTTOM_MS = 1500; private static readonly COPIED_MS = 1200; @@ -72,6 +75,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { setTimeout(() => this.scrollToBottom('smooth'), 0); } } + if (changes.messages || changes.completedExecutions || changes.loading) { + this.summaries = this.findSummaries(); + } if (changes.messages) { this.lastAnswerIndex = this.findLastAnswerIndex(); this.actionRunning = this.messages.some(message => message.from === 'ACTION' && message.data.status === 'RUNNING'); @@ -121,6 +127,46 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { this.approvalAction.emit($event); } + private findSummaries(): Record { + const summaries: Record = {}; + let entities: EntityId[] = []; + let seen = new Set(); + let lastAi = -1; + const close = (finished: boolean) => { + if (finished && lastAi >= 0 && entities.length) { + summaries[lastAi] = entities; + } + entities = []; + seen = new Set(); + lastAi = -1; + }; + const add = (ids?: EntityId[]) => (ids ?? []).forEach(id => { + const key = `${id.entityType}:${id.id}`; + if (!seen.has(key)) { + seen.add(key); + entities.push(id); + } + }); + this.messages.forEach((message, index) => { + switch (message.from) { + case 'USER': + close(true); + break; + case 'APPROVAL': + add((this.completedExecutions[message.data.executionId] ?? message.result)?.affectedEntities); + break; + case 'ACTION': + add(message.data.affectedEntities); + break; + case 'AI': + lastAi = index; + break; + } + }); + close(!this.loading); + return summaries; + } + private findLastAnswerIndex(): number { for (let i = this.messages.length - 1; i >= 0; i--) { const message = this.messages[i]; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 3e118c5a06..2d5ab54824 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -490,8 +490,12 @@ export class AiChatComponent implements OnInit, OnDestroy { } private finishAction(finished: ToolFinished): void { + if (finished.affectedEntities?.length) { + this.affectedEntities.push(...finished.affectedEntities); + } this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === finished.executionId - ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result}} + ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result, + affectedEntities: finished.affectedEntities}} : message)); if (!this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { this.setWork('going-through-results', true); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.html new file mode 100644 index 0000000000..7036f604f7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.html @@ -0,0 +1,31 @@ + +@if (rows().length) { +
    + @for (row of rows(); track row.key) { +
  • + @if (row.url) { + + + + } @else { + + + + } +
  • + } +
+} + + + + + {{ row.name }} + {{ row.meta }} + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.scss new file mode 100644 index 0000000000..98bdb491c8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.scss @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; +} + +.rows { + margin: 10px 0 0; + padding: 0; + list-style: none; + border: 1px solid var(--k-stroke); + border-radius: 12px; + overflow: hidden; + background: var(--tb-surface); + + li + li { + border-top: 1px solid var(--tb-line-soft); + } +} + +.row { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 14px; + color: var(--tb-ink); + text-decoration: none; + font-family: var(--tb-font); + + .icon { + flex: none; + width: 32px; + height: 32px; + border-radius: 8px; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--tb-line-soft); + color: var(--tb-ink-60); + + mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } + } + + .text { + display: flex; + flex-direction: column; + min-width: 0; + } + + .name { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .meta { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +a.row { + cursor: pointer; + + &:hover { + background: var(--tb-line-soft); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: -2px; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts new file mode 100644 index 0000000000..7412e5d1d8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { forkJoin, Observable, of, Subscription } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { EntityService } from '@core/http/entity.service'; +import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; +import { NotificationService } from '@core/http/notification.service'; +import { CalculatedFieldType } from '@shared/models/calculated-field.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { RequestConfig } from '@core/http/http-utils'; + +interface AiSummaryRow { + key: string; + icon: string; + name: string; + meta: string; + url?: string; +} + +const CONFIG: RequestConfig = {ignoreLoading: true, ignoreErrors: true}; + +const ICONS: Partial> = { + [EntityType.DEVICE]: 'memory', + [EntityType.ASSET]: 'domain', + [EntityType.DASHBOARD]: 'dashboard', + [EntityType.CALCULATED_FIELD]: 'functions', + [EntityType.NOTIFICATION_RULE]: 'notifications_active', + [EntityType.NOTIFICATION_TEMPLATE]: 'description', + [EntityType.NOTIFICATION_TARGET]: 'group' +}; + +const NOTIFICATION_PAGES: Partial> = { + [EntityType.NOTIFICATION_RULE]: '/notification/rules', + [EntityType.NOTIFICATION_TEMPLATE]: '/notification/templates', + [EntityType.NOTIFICATION_TARGET]: '/notification/recipients' +}; + +@Component({ + selector: 'tb-ai-run-summary', + templateUrl: './ai-run-summary.component.html', + styleUrls: ['./ai-run-summary.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRunSummaryComponent { + + entities = input.required(); + + rows = signal([]); + + private key = computed(() => this.entities().map(entity => `${entity.entityType}:${entity.id}`).join(',')); + + private entityService = inject(EntityService); + private calculatedFieldsService = inject(CalculatedFieldsService); + private notificationService = inject(NotificationService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + + private loading: Subscription; + + constructor() { + effect(() => { + this.key(); + const entities = untracked(() => this.entities()); + this.loading?.unsubscribe(); + this.loading = forkJoin(entities.map(entity => this.row(entity).pipe(catchError(() => of(null))))) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(rows => this.rows.set(rows.filter(row => !!row))); + }); + } + + private row(entity: EntityId): Observable { + const entityType = entity.entityType as EntityType; + const key = `${entityType}:${entity.id}`; + const icon = ICONS[entityType] ?? 'category'; + switch (entityType) { + case EntityType.CALCULATED_FIELD: + return this.calculatedFieldsService.getCalculatedFieldById(entity.id, CONFIG).pipe(map(field => { + const alarmRule = field.type === CalculatedFieldType.ALARM; + return { + key, + icon: alarmRule ? 'rule' : icon, + name: field.name, + meta: this.translate.instant(alarmRule ? 'ai-assistant.summary.alarm-rule' : 'ai-assistant.summary.calculated-field'), + url: alarmRule ? `/alarms/alarm-rules/${entity.id}` : `/calculatedFields/${entity.id}` + }; + })); + case EntityType.NOTIFICATION_RULE: + return this.notificationService.getNotificationRuleById(entity.id, CONFIG) + .pipe(map(rule => this.simpleRow(key, icon, rule.name, entityType, NOTIFICATION_PAGES[entityType]))); + case EntityType.NOTIFICATION_TEMPLATE: + return this.notificationService.getNotificationTemplateById(entity.id, CONFIG) + .pipe(map(template => this.simpleRow(key, icon, template.name, entityType, NOTIFICATION_PAGES[entityType]))); + default: + return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { + const row = this.simpleRow(key, icon, found?.name, entityType, + NOTIFICATION_PAGES[entityType] ?? (getEntityDetailsPageURL(entity.id, entityType) || undefined)); + const subtype = (found as {type?: string})?.type; + if (subtype && (entityType === EntityType.DEVICE || entityType === EntityType.ASSET)) { + row.meta = `${row.meta} · ${subtype}`; + } + return row; + })); + } + } + + private simpleRow(key: string, icon: string, name: string, entityType: EntityType, url?: string): AiSummaryRow | null { + if (!name) { + return null; + } + const translation = entityTypeTranslations.get(entityType)?.type; + return { + key, + icon, + name, + meta: translation ? this.translate.instant(translation) : entityType, + url + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index af5d695777..098f2fbb98 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -19,6 +19,7 @@ import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component'; import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; +import { AiRunSummaryComponent } from '@home/components/ai/ai-run-summary.component'; @NgModule({ declarations: [ @@ -37,7 +38,8 @@ import { AiActionLineComponent } from '@home/components/ai/ai-action-line.compon AiTipDirective, AiSpinComponent, AiWorkLineComponent, - AiActionLineComponent + AiActionLineComponent, + AiRunSummaryComponent ], imports: [ CommonModule, 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 0f3f650b9f..3bd6197468 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -121,6 +121,7 @@ export interface ToolFinished extends BaseChatToolEventData { status: 'SUCCESS' | 'FAILURE'; durationMs: number; result?: string; + affectedEntities?: Array; } export interface ToolFinishedEvent extends BaseChatEvent { @@ -138,6 +139,7 @@ export interface AiAction { startedAt: number; durationMs?: number; result?: string; + affectedEntities?: Array; } export interface ApprovalResult { 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 4160d5f34b..0e2688a878 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -969,6 +969,11 @@ "request": "Request", "result": "Result" }, + "summary": { + "made": "What this run made or changed", + "alarm-rule": "Alarm rule", + "calculated-field": "Calculated field" + }, "work": { "reading-request": "Reading the request", "going-through-results": "Going through the results", From b67f37bfa1096fe696651bdb8a0b8536ad56fa6f Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 16:34:52 +0200 Subject: [PATCH 006/183] feat: the AI chat follows the chat kit: kit records and run summary, approval cards with the change under review, action and working lines on the kit grid, kit markdown and messages, the scroll-to-end pill, header rename and scroll band, and composer details --- .../ai/ai-action-line.component.html | 48 +- .../ai/ai-action-line.component.scss | 78 +- .../components/ai/ai-action-line.component.ts | 38 +- .../home/components/ai/ai-action.models.ts | 77 +- .../ai/ai-approval-card.component.html | 146 ++-- .../ai/ai-approval-card.component.scss | 115 +-- .../ai/ai-approval-card.component.ts | 159 ++++- .../ai/ai-chat-messages.component.html | 28 +- .../ai/ai-chat-messages.component.scss | 214 ++++-- .../ai/ai-chat-messages.component.ts | 31 +- .../home/components/ai/ai-chat.component.html | 53 +- .../home/components/ai/ai-chat.component.scss | 227 +++++- .../home/components/ai/ai-chat.component.ts | 77 +- .../ai/ai-prompt-input.component.html | 2 +- .../ai/ai-prompt-input.component.scss | 103 ++- .../ai/ai-prompt-input.component.ts | 4 +- .../home/components/ai/ai-record.component.ts | 49 ++ .../ai/ai-run-summary.component.html | 31 - .../ai/ai-run-summary.component.scss | 84 --- .../components/ai/ai-run-summary.component.ts | 110 ++- .../home/components/ai/ai-spin.component.scss | 14 +- .../components/ai/ai-work-line.component.scss | 49 +- .../components/ai/ai-work-line.component.ts | 30 +- .../modules/home/components/ai/ai.module.ts | 4 +- .../ai-assistant/ai-assistant.component.html | 2 +- .../ai-assistant/ai-assistant.component.scss | 4 + .../src/app/shared/models/ai-chat.models.ts | 20 + .../assets/locale/locale.constant-en_US.json | 137 +++- ui-ngx/src/theme/ai-theme.scss | 669 +++++++++++++++++- 29 files changed, 2015 insertions(+), 588 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.scss diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html index 0ae45625d4..faba8984b3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -4,27 +4,33 @@ SPDX-License-Identifier: BUSL-1.1 --> -@if (action().status === 'RUNNING') { - -} @else { -
- - {{ outcome() }} - @if (duration()) { - {{ duration() }} - } -
- @if (hasDetails()) { -
- {{ 'ai-assistant.action.details' | translate }} - @if (request()) { -
{{ 'ai-assistant.action.request' | translate }}
-
{{ request() }}
- } - @if (result()) { -
{{ 'ai-assistant.action.result' | translate }}
-
{{ result() }}
+@switch (action().status) { + @case ('RUNNING') { + + } + @case ('STOPPED') { + + } + @default { +
+ + {{ outcome() }} + @if (duration()) { + {{ duration() }} } -
+
+ @if (hasDetails()) { +
+ {{ 'ai-assistant.action.details' | translate }} + @if (request()) { +
{{ 'ai-assistant.action.request' | translate }}
+
{{ request() }}
+ } + @if (result()) { +
{{ 'ai-assistant.action.result' | translate }}
+
{{ result() }}
+ } +
+ } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss index f3e2dd07f6..7defbeeb4c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -2,7 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - font-family: var(--tb-font); + font-family: var(--tb-mono); + font-size: 15px; letter-spacing: var(--chat-text-ls); } @@ -10,16 +11,20 @@ display: flex; align-items: flex-start; gap: 8px; + margin-top: 2px; + font-family: var(--tb-font); font-size: var(--chat-line); line-height: var(--chat-line-lh); - color: var(--tb-ink-76); + color: var(--tb-ink); .mark { flex: none; - width: 16px; - height: 16px; - font-size: 16px; - margin-block: calc((var(--chat-line-lh) - 16px) / 2); + display: flex; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + margin-top: 0; color: var(--tb-ok); } @@ -29,10 +34,11 @@ } .dur { + flex: none; margin-left: auto; - padding-left: 12px; font-family: var(--tb-mono); - font-size: var(--chat-meta); + font-size: 12px; + line-height: var(--chat-line-lh); color: var(--k-faint); white-space: nowrap; } @@ -42,55 +48,11 @@ color: var(--tb-crit); } -:host(.stopped) .out { - color: var(--tb-text-secondary); - - .mark { - color: var(--tb-ink-38); - } -} - -.disc { - margin: 2px 0 0 24px; +.tb-disc.tb-disc-details { + margin: 4px 0 0 28px; > summary { - list-style: none; - display: flex; - align-items: center; - gap: 4px; - width: fit-content; - cursor: pointer; - font-size: var(--chat-meta); - line-height: var(--chat-meta-lh); - color: var(--tb-ink-60, var(--tb-text-secondary)); - - &::-webkit-details-marker { - display: none; - } - - &::before { - content: 'chevron_right'; - flex: none; - width: 18px; - height: 18px; - font: 18px/18px 'Material Icons'; - color: var(--tb-ink-38); - transition: transform .15s ease; - } - - &:hover, &:hover::before { - color: var(--tb-ink); - } - - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 2px; - border-radius: 4px; - } - } - - &[open] > summary::before { - transform: rotate(90deg); + color: var(--tb-ink-76); } .part { @@ -115,10 +77,4 @@ overflow-wrap: anywhere; color: var(--tb-ink-76); } - - @media (prefers-reduced-motion: reduce) { - > summary::before { - transition: none; - } - } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index 9f04d2129c..a86fff9439 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -29,30 +29,21 @@ export class AiActionLineComponent { words = computed(() => aiActionWords(this.action().tool, this.action().arguments)); - running = computed(() => this.translate.instant(this.words().key + '.run', this.words().params)); + more = input(0); + + private runWords = computed(() => this.translate.instant(this.words().key + '.run', this.words().params)); + + running = computed(() => this.more() > 0 + ? this.translate.instant('ai-assistant.work.more', {words: this.runWords(), count: this.more()}) + : this.runWords()); outcome = computed(() => { const action = this.action(); const words = this.words(); - switch (action.status) { - case 'SUCCESS': - return this.translate.instant(words.key + '.done', words.params); - case 'FAILURE': - return this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.running())}); - default: - return this.translate.instant('ai-assistant.work.stopped', {words: this.lowerFirst(this.running())}); - } - }); - - icon = computed(() => { - switch (this.action().status) { - case 'SUCCESS': - return 'check'; - case 'FAILURE': - return 'error_outline'; - default: - return 'block'; + if (action.status === 'FAILURE') { + return this.reason(action.result) ?? this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); } + return this.translate.instant(words.key + '.done', words.params); }); duration = computed(() => this.action().durationMs !== undefined ? aiActionDuration(this.action().durationMs) : ''); @@ -63,6 +54,15 @@ export class AiActionLineComponent { hasDetails = computed(() => !!this.request() || !!this.result()); + private reason(result?: string): string | undefined { + const text = result?.trim(); + if (!text || text.startsWith('{') || text.startsWith('[')) { + return undefined; + } + const line = text.split('\n')[0].trim(); + return line.length > 300 ? line.slice(0, 300) + '…' : line; + } + private lowerFirst(words: string): string { return words ? words.charAt(0).toLocaleLowerCase() + words.slice(1) : words; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index c79b097858..1c6fde06fd 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -28,9 +28,6 @@ const TOOL_WORDS: Record = { delete_attributes: 'delete-attributes', read_entity_relations: 'read-relations', read_device_credentials: 'read-credentials', - save_device: 'save-device', - save_calculated_field: 'save-calculated-field', - save_alarm_rule: 'save-alarm-rule', create_dashboard: 'create-dashboard', update_dashboard: 'update-dashboard', add_dashboard_state: 'add-dashboard-state', @@ -42,14 +39,10 @@ const TOOL_WORDS: Record = { update_dashboard_filter: 'update-dashboard-filter', read_dashboard_filter: 'read-dashboard-filter', read_dashboard_overview: 'read-dashboard', - add_dashboard_widgets: 'add-widgets', update_dashboard_widget: 'update-widget', place_dashboard_widgets: 'place-widgets', read_dashboard_widget: 'read-widget', read_dashboard_html_page: 'read-dashboard-page', - save_notification_target: 'save-notification-target', - save_notification_template: 'save-notification-template', - save_notification_rule: 'save-notification-rule', search_iot_hub_devices: 'search-iot-hub', read_transport_endpoints: 'read-connection-settings', read_device_connect_commands: 'read-connection-settings', @@ -62,6 +55,15 @@ const GENERATING_TOOLS: Record = { research_device_connectivity: 'research-device' }; +const SAVED_KINDS: Record = { + save_device: ['device', ''], + save_calculated_field: ['calculated-field', ''], + save_alarm_rule: ['alarm-rule', 'alarmRule'], + save_notification_target: ['notification-target', 'target'], + save_notification_template: ['notification-template', 'template'], + save_notification_rule: ['notification-rule', 'rule'] +}; + const SEARCHED_TYPES: Record = { DEVICE: 'search-devices', ASSET: 'search-assets', @@ -93,7 +95,13 @@ export function aiActionWords(tool: string, args: unknown): AiActionWords { if (GENERATING_TOOLS[tool]) { return {key: ACTION_PREFIX + GENERATING_TOOLS[tool], kind: 'gen'}; } + if (SAVED_KINDS[tool]) { + const [kind, nested] = SAVED_KINDS[tool]; + return {key: ACTION_PREFIX + (hasId(nested ? values[nested] : values) ? 'update-' : 'create-') + kind, kind: 'think'}; + } switch (tool) { + case 'add_dashboard_widgets': + return {key: ACTION_PREFIX + (Array.isArray(values.widgets) && values.widgets.length === 1 ? 'add-widget' : 'add-widgets'), kind: 'think'}; case 'search_entities': return {key: ACTION_PREFIX + searchedWords(values), kind: 'think'}; case 'read_timeseries': @@ -121,7 +129,7 @@ export function aiActionDuration(ms: number): string { } export function aiWorkClock(ms: number): string { - const seconds = Math.floor(ms / 1000); + const seconds = Math.round(ms / 1000); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; } @@ -140,6 +148,19 @@ export function aiActionDetail(value: unknown): string { return JSON.stringify(value, null, 2); } +function hasId(value: unknown): boolean { + let object = value; + if (typeof value === 'string') { + try { + object = JSON.parse(value); + } catch { + return false; + } + } + const id = (object as {id?: unknown})?.id; + return !!id && (typeof id === 'string' || typeof (id as {id?: unknown}).id === 'string'); +} + function searchedWords(values: Record): string { const filter = values.entityFilter ?? values; const types = new Set(); @@ -180,3 +201,43 @@ function siteOf(url: unknown): string | undefined { return undefined; } } + +export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution'; + +export interface AiEntityKind { + icon: string; + palette: AiEntityPalette; +} + +const ENTITY_KINDS: Record = { + DEVICE: {icon: 'memory', palette: 'device'}, + DEVICE_PROFILE: {icon: 'category', palette: 'device'}, + ASSET: {icon: 'domain', palette: 'device'}, + ASSET_PROFILE: {icon: 'category', palette: 'device'}, + INTEGRATION: {icon: 'input', palette: 'path'}, + CONVERTER: {icon: 'transform', palette: 'path'}, + CALCULATED_FIELD: {icon: 'functions', palette: 'path'}, + RULE_CHAIN: {icon: 'account_tree', palette: 'chain'}, + ALARM_RULE: {icon: 'rule', palette: 'rule'}, + ALARM: {icon: 'notification_important', palette: 'rule'}, + NOTIFICATION_RULE: {icon: 'notifications_active', palette: 'rule'}, + NOTIFICATION_TEMPLATE: {icon: 'description', palette: 'path'}, + NOTIFICATION_TARGET: {icon: 'group', palette: 'people'}, + DASHBOARD: {icon: 'dashboard', palette: 'view'}, + DASHBOARD_WIDGET: {icon: 'widgets', palette: 'view'}, + DASHBOARD_STATE: {icon: 'tab', palette: 'view'}, + DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'}, + WIDGET_TYPE: {icon: 'widgets', palette: 'view'}, + CUSTOMER: {icon: 'supervisor_account', palette: 'people'}, + USER: {icon: 'account_circle', palette: 'people'}, + TENANT: {icon: 'business', palette: 'people'} +}; + +export function aiEntityKind(entityType: string, alarmRule = false): AiEntityKind { + return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'solution'}; +} + +export function aiEntityIcon(entityType: string, alarmRule = false): string { + return aiEntityKind(entityType, alarmRule).icon; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index e781c64d4f..53724d6f5c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -4,54 +4,106 @@ SPDX-License-Identifier: BUSL-1.1 --> -@switch (state) { - @case ('pending') { -
{{ data.title ?? ('ai-assistant.action-approval-required' | translate) }}
-
{{ data.message }}
-
- - -
- @if (denying) { - - } - - } - @case ('executing') { -
- - {{ data.executing ?? ('ai-assistant.processing' | translate) }} -
- } - @case ('approved') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.approved' | translate) }} -
+
+
{{ headText }}
+ @if (review) { + } - @case ('denied') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.denied' | translate) }} -
+ @switch (state) { + @case ('pending') { + @if (!review) { +

{{ data.message }}

+ } + @if (facts.length) { +
+ @for (fact of facts; track $index) { +
@if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
+
@if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
+ } +
+ } + @if (changes.length) { + + + + + + + + + + @for (change of changes; track $index) { + + + + + + } + + @if (unchanged.length && showUnchanged) { + + @for (same of unchanged; track $index) { + + + + + } + + } +
{{ 'ai-assistant.review.current' | translate }}{{ 'ai-assistant.review.new' | translate }}
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} }{{ change.current }}{{ change.value }}
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }{{ same.value }}
+ @if (unchanged.length) { + + } + } +
+ + +
+ @if (denying) { +
+ +
+ } + } + @case ('denied') { +

{{ 'ai-assistant.review.denied-text' | translate }}

+ } + @case ('expired') { +

{{ 'ai-assistant.review.expired-text' | translate }}

+
+ +
+ } } - @case ('error') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.error' | translate) }} -
+ @if (data.time) { + } +
+@if (outcome; as result) { +
+ + {{ result.text }} +
} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss index a4133a7c35..3853f918d6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss @@ -2,108 +2,33 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - border: 1px solid var(--k-stroke); - border-radius: 12px; - padding: var(--chat-card-pad); - background: var(--tb-surface); +} + +.k-out { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 10px; font-family: var(--tb-font); - letter-spacing: var(--chat-text-ls); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); color: var(--tb-ink); - &.executing { - color: var(--k-grey); - } - - &.approved { - color: var(--tb-ok-text); - background-color: var(--tb-ok-tint); - } - - &.denied { - color: var(--tb-text-secondary); - background-color: var(--tb-line-soft); + .k-out-mark { + flex: none; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + color: var(--tb-ok); } - &.error { + &.fail .k-out-mark { color: var(--tb-crit); - background-color: var(--tb-crit-tint); - } - - .approval-title { - margin-bottom: 8px; - font-weight: 500; - font-size: var(--chat-head); - line-height: var(--chat-head-lh); - } - - .approval-content { - margin-bottom: 16px; - font-size: var(--chat-line); - line-height: var(--chat-line-lh); - color: var(--tb-text-secondary); - } - - .approval-actions { - display: flex; - gap: 8px; - justify-content: flex-end; - - .approved { - flex: 1; - --mat-button-filled-label-text-color: var(--ai-on-action); - --mat-button-filled-container-color: var(--ai-action); - } - - .danger { - flex: 1; - --mat-button-filled-label-text-color: var(--ai-on-action); - --mat-button-filled-container-color: var(--tb-crit); - } - - .denied { - flex: 1; - --mat-button-outlined-label-text-color: var(--tb-ink); - --mat-button-outlined-outline-color: var(--k-stroke-hover); - } - } - - .deny-line { - display: block; - width: 100%; - height: 36px; - box-sizing: border-box; - margin-top: 8px; - padding: 0 12px; - border: 0; - border-radius: 8px; - outline: 0; - background: var(--tb-surface); - box-shadow: inset 0 0 0 1px var(--k-stroke-hover); - font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); - color: var(--tb-ink); - - &:focus { - box-shadow: inset 0 0 0 1.5px var(--ai-focus), 0 0 0 3px var(--ai-focus-shadow); - } - - &::placeholder { - color: var(--tb-text-secondary); - } - } - - .approve-all { - width: 100%; - margin-top: 8px; - --mat-button-text-label-text-color: var(--tb-text-secondary); - --mat-button-text-container-height: var(--chat-control); } - .approval-result { - display: flex; - align-items: center; - gap: 8px; - font-size: var(--chat-line); - font-weight: 500; - line-height: var(--chat-line-lh); + .k-out-say { + min-width: 0; + overflow-wrap: anywhere; } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 4590fc5bfe..fa4b1da4b3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -5,7 +5,6 @@ import { Component, ElementRef, EventEmitter, - HostBinding, inject, Input, OnChanges, @@ -13,14 +12,41 @@ import { SimpleChanges, ViewChild } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; import { + AiApprovalReview, + AiReviewField, ApprovalResult, ToolApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; -export type ApprovalCardState = 'pending' | 'executing' | 'approved' | 'denied' | 'error'; +export type ApprovalCardState = 'pending' | 'approved' | 'auto' | 'denied' | 'expired'; + +export interface AiReviewRow { + label: string; + labelCode: boolean; + valueCode: boolean; + current?: string; + value: string; +} + +const MAX_FIELDS = 5; + +const DETAIL_TOKENS = new Set(['server-attributes', 'shared-attributes']); + +const VALUE_TOKENS: Record = { + undo: ['none'], + clears: ['yes', 'no'] +}; + +const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); + +const OWN_TYPE_LABELS = new Set(['DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER']); + +const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); @Component({ selector: 'tb-ai-approval-card', @@ -40,63 +66,119 @@ export class AiApprovalCardComponent implements OnChanges { @ViewChild('denyInput') denyInput: ElementRef; + @Output() approvalAction = new EventEmitter(); + + @Output() askAgain = new EventEmitter(); + denying = false; - @Output() approvalAction = new EventEmitter(); + showUnchanged = false; - @HostBinding('class') state: ApprovalCardState = 'pending'; + state: ApprovalCardState = 'pending'; + + private autoApproved = false; private readonly cd = inject(ChangeDetectorRef); + private readonly translate = inject(TranslateService); ngOnChanges(changes: SimpleChanges): void { if (this.autoApprove && this.state === 'pending' && !this.completedExecution) { + this.autoApproved = true; this.approve(); } if (this.answered && this.state === 'pending' && !this.completedExecution) { this.denying = false; - this.state = 'executing'; + this.state = 'denied'; } if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) { const result = this.completedExecution; - if (result.approvalStatus === ToolApprovalResult.DENIED || result.approvalStatus === ToolApprovalResult.TIMEOUT) { + if (result.approvalStatus === ToolApprovalResult.TIMEOUT) { + this.state = 'expired'; + } else if (result.approvalStatus === ToolApprovalResult.DENIED) { this.state = 'denied'; - } else if (result.approvalStatus === ToolApprovalResult.APPROVED && result.executionStatus === 'SUCCESS') { - this.state = 'approved'; } else { - this.state = 'error'; + this.state = this.autoApproved ? 'auto' : 'approved'; } this.cd.detectChanges(); } } - get isDestructive(): boolean { - return this.data.destructive; + get review(): AiApprovalReview | undefined { + return this.data.review; } - get approveIcon(): string { - return this.data.icon || (this.isDestructive ? 'delete' : 'check'); + get isDestructive(): boolean { + return this.data.destructive; } - get resultIcon(): string { - if (this.completedExecution?.icon) { - return this.completedExecution.icon; - } + get headIcon(): string { switch (this.state) { case 'approved': - return this.approveIcon; + return 'check_circle'; + case 'auto': + return 'bolt'; case 'denied': return 'block'; + case 'expired': + return 'timer_off'; default: - return 'error_outline'; + return 'rate_review'; } } - approve(): void { - this.emitApproval(); + get headText(): string { + return this.translate.instant('ai-assistant.review.head.' + this.state); + } + + get outcome(): {failed: boolean; text: string} | null { + const result = this.completedExecution; + if (!result || result.approvalStatus !== ToolApprovalResult.APPROVED) { + return null; + } + const failed = result.executionStatus !== 'SUCCESS'; + return {failed, text: result.message || this.translate.instant(failed ? 'ai-assistant.error' : 'ai-assistant.approved')}; + } + + get alarmRule(): boolean { + return this.review?.detail === 'alarm-rule'; + } + + get meta(): string { + const review = this.review; + if (!review) { + return ''; + } + const parts = [this.alarmRule ? this.translate.instant('ai-assistant.review.type.ALARM_RULE') : this.typeLabel(review.entityType)]; + if (review.detail && !this.alarmRule) { + parts.push(DETAIL_TOKENS.has(review.detail) ? this.translate.instant('ai-assistant.review.detail.' + review.detail) : review.detail); + } + if (review.target) { + parts.push(this.translate.instant(PROFILE_TYPES.has(review.entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', + {name: review.target})); + } + return parts.join(' · '); + } + + get facts(): AiReviewRow[] { + return this.rows('FACT').slice(0, MAX_FIELDS); + } + + get changes(): AiReviewRow[] { + return this.rows('CHANGE'); + } + + get unchanged(): AiReviewRow[] { + return this.rows('UNCHANGED'); } - approveAll(): void { - this.emitApproval(true); + get recordClosed(): boolean { + return this.state === 'pending' || this.state === 'denied' || this.state === 'expired'; + } + + approve(): void { + this.state = this.autoApproved ? 'auto' : 'approved'; + this.denying = false; + this.approvalAction.emit({executionId: this.data.executionId, approved: true}); } deny(): void { @@ -111,7 +193,7 @@ export class AiApprovalCardComponent implements OnChanges { sendDeny(words: string): void { const reason = words.trim(); this.denying = false; - this.state = 'executing'; + this.state = 'denied'; this.approvalAction.emit(reason ? {executionId: this.data.executionId, approved: false, reason} : {executionId: this.data.executionId, approved: false}); @@ -121,8 +203,31 @@ export class AiApprovalCardComponent implements OnChanges { this.denying = false; } - private emitApproval(autoApprove = false): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: true, autoApprove}); + private rows(kind: AiReviewField['kind']): AiReviewRow[] { + return (this.review?.fields ?? []).filter(field => field.kind === kind).map(field => ({ + label: field.name ?? this.translate.instant('ai-assistant.review.field.' + field.id), + labelCode: !!field.name, + valueCode: CODE_FIELDS.has(field.id) && field.value !== undefined && field.value !== null, + current: kind === 'CHANGE' ? this.value(field, field.current) : undefined, + value: this.value(field, field.value) + })); + } + + private value(field: AiReviewField, value: string | undefined): string { + if (value === undefined || value === null) { + return this.translate.instant('ai-assistant.review.not-set'); + } + if (field.id && VALUE_TOKENS[field.id]?.includes(value)) { + return this.translate.instant(`ai-assistant.review.value.${field.id}-${value}`); + } + return value; + } + + private typeLabel(entityType: string): string { + if (OWN_TYPE_LABELS.has(entityType)) { + return this.translate.instant('ai-assistant.review.type.' + entityType); + } + const translation = entityTypeTranslations.get(entityType as EntityType)?.type; + return translation ? this.translate.instant(translation) : entityType; } } 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 1ee961e241..89c8e53f84 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 @@ -16,14 +16,16 @@ } @if (msg.time) {
- +
}
} @else if (msg.from === 'ACTION') { -
- -
+ @if (msg.data.status !== 'RUNNING' || $index === runningLead) { +
+ +
+ } } @else {
@if (msg.from === 'APPROVAL') { @@ -32,10 +34,11 @@ [completedExecution]="getCompletedExecution(msg)" [autoApprove]="autoApprove" [answered]="!!denyReasons[getApprovalData(msg).executionId]" - (approvalAction)="approval($event)"> + (approvalAction)="approval($event)" + (askAgain)="askAgain.emit()"> } @else if (msg.status === 'INCOMPLETE') { -
+
warning_amber {{ msg.content }}
@@ -44,15 +47,16 @@ } } @else {
- - +
+ + @if (summaries[$index]; as entities) { + + } +
- @if (summaries[$index]; as entities) { - - }
@if (msg.time) { - + } + + } @else { - {{ chat.title }} + + + + @if (level(); as level) { @@ -38,7 +58,7 @@ } @if (chat() && !renaming()) { - @@ -47,7 +67,7 @@
-
+
@if (messages().length || loading()) { + (approvalAction)="onApprovalAction($event)" + (askAgain)="onAskAgain()"> } @else if (!chatId()) {
@@ -71,10 +92,22 @@
}
+ @if (pill(); as current) { + + } ([]); @@ -112,6 +112,32 @@ export class AiChatComponent implements OnInit, OnDestroy { work = signal(undefined); + scrolled = signal(false); + + private atEnd = signal(true); + + private newTurns = signal(0); + + private seenMessages = 0; + + pill = computed<{mode: 'work' | 'new'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + if (this.loading() && !this.waitingApproval()) { + const running = this.messages().filter((message): message is ActionChatMessage => + message.from === 'ACTION' && message.data.status === 'RUNNING'); + if (running.length) { + const words = aiActionWords(running[0].data.tool, running[0].data.arguments); + return {mode: 'work', kind: words.kind, label: this.translate.instant(words.key + '.run', words.params), count: 0}; + } + const work = this.work(); + return {mode: 'work', kind: 'think', label: work ? this.translate.instant('ai-assistant.work.' + work.moment) : '', count: 0}; + } + const count = this.newTurns(); + return count ? {mode: 'new', kind: 'think', label: this.translate.instant('ai-assistant.go-to-end'), count} : null; + }); + private answeredApprovals = signal>(new Set()); waitingApproval = computed(() => { @@ -150,6 +176,11 @@ export class AiChatComponent implements OnInit, OnDestroy { private affectedEntities: EntityId[] = []; private logScrollBottom: number | undefined; + private newTurnsEffect = effect(() => { + this.messages(); + untracked(() => this.countNewTurns()); + }); + private chatIdEffect = effect(() => { const chatId = this.chatId(); untracked(() => this.show(chatId)); @@ -311,6 +342,12 @@ export class AiChatComponent implements OnInit, OnDestroy { this.aiChat.resolveToolApproval(result, {ignoreLoading: true, ignoreErrors: true}).subscribe(); } + onAskAgain(): void { + if (!this.loading()) { + this.sendMsgFromUser({message: this.translate.instant('ai-assistant.review.ask-again-message'), resources: []}); + } + } + sendMsgFromUser(prompt: AiPromptMessage): void { const waiting = this.waitingApproval(); if (waiting) { @@ -374,6 +411,7 @@ export class AiChatComponent implements OnInit, OnDestroy { if (this.clientContext()) { request.clientContext = this.clientContext(); } + this.setWork('reading-request', true); this.loading.set(true); return startOrContinue$.pipe( tap(() => this.startLoading()), @@ -475,6 +513,39 @@ export class AiChatComponent implements OnInit, OnDestroy { return of(event); } + onLogScroll(area: HTMLElement): void { + const scrolled = area.scrollTop > 0; + if (scrolled !== this.scrolled()) { + this.scrolled.set(scrolled); + } + const atEnd = area.scrollHeight - area.scrollTop - area.clientHeight <= 40; + if (atEnd !== this.atEnd()) { + this.atEnd.set(atEnd); + } + if (atEnd) { + this.newTurns.set(0); + this.seenMessages = this.messages().length; + } + } + + goToEnd(area: HTMLElement): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + area.scrollTo({top: area.scrollHeight, behavior: reduce ? 'auto' : 'smooth'}); + } + + private countNewTurns(): void { + const total = this.messages().length; + if (this.atEnd() || total <= this.seenMessages) { + this.seenMessages = total; + return; + } + const added = this.messages().slice(this.seenMessages).filter(message => message.from === 'AI').length; + this.seenMessages = total; + if (added) { + this.newTurns.update(count => count + added); + } + } + private startAction(started: ToolStarted): void { if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId)) { return; 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 fe22fc36a4..edabd20924 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 @@ -54,7 +54,7 @@ [attr.aria-label]="'ai-assistant.stop' | translate" tb-popover [tbAiTip]="stopTip" (click)="stop()"> - + } @else {
} @else { -
.tb-popover-content > .tb-popover-arrow { - border-right-color: var(--ai-dark); - border-bottom-color: var(--ai-dark); + border-right-color: #1f2a31; + border-bottom-color: #1f2a31; box-shadow: none; } &[class*='tb-popover-placement-bottom'] > .tb-popover-content > .tb-popover-arrow { - border-top-color: var(--ai-dark); - border-left-color: var(--ai-dark); + border-top-color: #1f2a31; + border-left-color: #1f2a31; box-shadow: none; } @@ -423,7 +424,7 @@ width: max-content; max-width: min(248px, calc(100vw - 16px)); padding: 9px 12px 10px; - color: var(--ai-on-dark); + color: #d5dde2; font: 400 12px/17px var(--tb-font); letter-spacing: .1px; @@ -456,7 +457,7 @@ } .tip-sub { - color: color-mix(in srgb, var(--ai-on-dark) 70%, transparent); + color: #9fadb7; } .tip-head { @@ -511,3 +512,657 @@ } } } + +:root { + --entity-device-bg: #e9efff; + --entity-device-fg: #535eb8; + --entity-path-bg: #dbf5ff; + --entity-path-fg: #007592; + --entity-chain-bg: #f7eaff; + --entity-chain-fg: #814ea4; + --entity-rule-bg: #ffebdf; + --entity-rule-fg: #a34d16; + --entity-view-bg: #e0f7e5; + --entity-view-fg: #2d7b48; + --entity-people-bg: #ffe9f1; + --entity-people-fg: #a0446d; + --entity-solution-bg: #e9f1fb; + --entity-solution-fg: #586a83; +} + +.tb-rec { + min-width: 0; + font-family: var(--tb-font, Roboto, sans-serif); + + &.line { + display: flex; + align-items: center; + gap: 8px; + width: fit-content; + max-width: 100%; + min-height: 32px; + padding: 3px 10px 3px 5px; + box-sizing: border-box; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + + .tb-rec-meta { + flex-shrink: 100000; + min-width: 72px; + } + + .tb-state { + flex: none; + } + } + + &[data-pal="device"] .tb-rec-tile { background: var(--entity-device-bg); color: var(--entity-device-fg); } + &[data-pal="path"] .tb-rec-tile { background: var(--entity-path-bg); color: var(--entity-path-fg); } + &[data-pal="chain"] .tb-rec-tile { background: var(--entity-chain-bg); color: var(--entity-chain-fg); } + &[data-pal="rule"] .tb-rec-tile { background: var(--entity-rule-bg); color: var(--entity-rule-fg); } + &[data-pal="view"] .tb-rec-tile { background: var(--entity-view-bg); color: var(--entity-view-fg); } + &[data-pal="people"] .tb-rec-tile { background: var(--entity-people-bg); color: var(--entity-people-fg); } + &[data-pal="solution"] .tb-rec-tile { background: var(--entity-solution-bg); color: var(--entity-solution-fg); } +} + +.tb-rec-tile { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: 24px; + height: 24px; + border-radius: 6px; + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink-76); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + color: inherit; + } +} + +.tb-rec-name { + min-width: 0; + flex: 0 1 auto; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--tb-ink); + font-weight: 500; + text-decoration: none; +} + +.tb-rec a.tb-rec-name { + font-weight: 500; + color: var(--tb-ink); + border-bottom: 0; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + transition: text-decoration-color .15s ease; + + &:hover, &:focus, &:focus-visible { + border-bottom: 0; + color: var(--tb-ink); + text-decoration-color: var(--tb-ink-54); + } +} + +.tb-rec-meta { + flex: 0 1 auto; + min-width: 0; + font-size: 12px; + line-height: 16px; + color: var(--tb-ink-76); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.tb-state { + display: inline-flex; + align-items: center; + gap: 6px; + height: 24px; + padding: 0 10px 0 8px; + border-radius: 12px; + font-size: 12px; + line-height: 16px; + font-weight: 500; + letter-spacing: .2px; + color: #fff; + background: var(--tb-ink-54); + white-space: nowrap; + vertical-align: middle; + + i { + width: 7px; + height: 7px; + border-radius: 50%; + background: currentColor; + } +} + +.tb-rec .tb-state { + height: 20px; + gap: 5px; + padding: 0 8px 0 7px; + border-radius: 10px; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + letter-spacing: .1px; + color: var(--tb-ok-text); + background: color-mix(in srgb, var(--tb-ok) 10%, transparent); + box-shadow: none; + + i { + width: 6px; + height: 6px; + } + + &.off { + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + } +} + +.tb-facts { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + align-items: baseline; + gap: 2px 12px; + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + + dt { + color: var(--tb-text-muted); + font-size: var(--chat-meta); + } + + dd { + margin: 0; + color: var(--tb-ink); + } +} + +.tb-more { + display: inline-flex; + align-items: center; + gap: 4px; + margin: 4px 0 0 -4px; + padding: 2px 6px 2px 4px; + border: 0; + border-radius: 6px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-primary-500); + cursor: pointer; + + .mat-icon { + width: 16px; + height: 16px; + font-size: 16px; + line-height: 16px; + } + + &:hover { + background: rgba(0, 0, 0, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } +} + +.tb-disc { + > summary { + list-style: none; + display: flex; + align-items: center; + gap: 4px; + width: fit-content; + cursor: pointer; + font-family: var(--tb-font); + color: var(--tb-ink-60); + + &::-webkit-details-marker { + display: none; + } + + &::before { + content: 'chevron_right'; + flex: none; + width: 18px; + height: 18px; + font: 18px/18px 'Material Icons'; + color: var(--tb-ink-38); + transition: transform .15s ease; + } + + &:hover, &:hover::before { + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-500); + outline-offset: 2px; + border-radius: 4px; + } + } + + &[open] > summary::before { + transform: rotate(90deg); + } + + &.tb-disc-details { + margin-top: 6px; + + > summary { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + } + + > :not(summary) { + margin-top: 8px; + } + } +} + +.k-recs { + display: grid; + gap: 6px; + margin-top: 14px; + + .tb-rec { + margin: 0; + } +} + +.k-time { + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); + font-variant-numeric: tabular-nums; +} + +.k-review { + position: relative; + padding: calc(var(--chat-card-pad) - 2px) var(--chat-card-pad); + background: var(--tb-surface); + border: 1px solid var(--k-stroke); + border-radius: 12px; + font-family: var(--tb-font); + font-size: 14px; + line-height: 20px; + letter-spacing: .25px; + color: var(--tb-ink); + + > .k-head { + display: flex; + align-items: center; + gap: 6px; + padding-right: 44px; + font-size: var(--chat-head); + line-height: var(--chat-head-lh); + font-weight: 500; + color: var(--tb-ink); + + > .mat-icon { + margin-top: 1px; + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); + line-height: var(--chat-icon); + color: var(--tb-ink-54); + } + } + + > .k-time { + position: absolute; + right: 16px; + top: 14px; + margin-left: 8px; + } + + .tb-rec.line { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto; + column-gap: 12px; + row-gap: 2px; + align-items: center; + width: auto; + margin: 0; + padding: 10px 0; + border: 0; + border-top: 1px solid var(--tb-line); + border-radius: 0; + background: none; + + .tb-rec-tile { + width: 40px; + height: 40px; + border-radius: 10px; + grid-row: 1 / span 2; + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + line-height: 22px; + } + } + + .tb-rec-name { + grid-column: 2; + grid-row: 1; + font-size: var(--chat-line); + } + + .tb-rec-meta { + grid-column: 2; + grid-row: 2; + min-width: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + } + + > .tb-state { + grid-column: 3; + grid-row: 1 / span 2; + } + + &.closed { + border-bottom: 1px solid var(--tb-line); + } + } + + > .k-head + .tb-rec.line { + margin-top: 10px; + } + + &.auto { + padding: 4px 0 2px; + background: transparent; + border: 0; + + > .k-head { + color: var(--tb-text-secondary); + font-size: var(--chat-line); + } + } + + &.done > .k-head > .mat-icon { + color: var(--tb-ok); + } + + &.failed > .k-head > .mat-icon { + color: var(--tb-crit); + } + + &.expired > .k-head, + &.denied > .k-head { + color: var(--tb-text-secondary); + } +} + +.k-review-p { + margin: 8px 0 0; + letter-spacing: .25px; + font-size: 14.5px; + line-height: 21px; + color: var(--tb-ink); + + .k-review.expired &, + .k-review.denied & { + color: var(--tb-text-secondary); + } +} + +.k-fields { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + align-items: baseline; + gap: 6px 14px; + margin: 12px 0 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + + dt { + color: var(--tb-ink-76); + } + + dd { + margin: 0; + color: var(--tb-ink); + overflow-wrap: anywhere; + } +} + +.k-review code, +.k-diff code { + display: inline-block; + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: 14px; + line-height: 18px; + color: var(--tb-ink); + white-space: normal; + overflow-wrap: anywhere; +} + +.k-diff { + border-collapse: collapse; + margin: 12px 0 0; + font-size: 15px; + line-height: 22px; + + thead th { + padding: 0 24px 4px 0; + font: 500 12px/16px var(--tb-font); + letter-spacing: .4px; + text-transform: uppercase; + color: var(--tb-text-muted); + text-align: left; + } + + tbody th { + padding: 5px 24px 5px 0; + font-size: 15px; + font-weight: 400; + color: var(--tb-text-muted); + text-align: left; + vertical-align: baseline; + } + + td { + padding: 5px 24px 5px 0; + font-size: 15px; + vertical-align: baseline; + white-space: nowrap; + + &:last-child { + padding-right: 0; + } + } + + .k-diff-was { + color: var(--tb-text-secondary); + } + + .k-diff-now span { + margin-left: -6px; + padding: 1px 6px; + border-radius: 4px; + background: var(--ai-teal-50); + color: var(--tb-ink); + font-weight: 500; + } + + .k-diff-same { + td { + color: var(--tb-text-secondary); + white-space: normal; + } + + tr:first-child > * { + padding-top: 9px; + } + } +} + +.k-actions { + display: flex; + align-items: center; + gap: 10px; + margin-top: 14px; + + .mdc-button { + height: 36px; + gap: 8px; + border: 1px solid transparent; + border-radius: 4px; + line-height: 36px; + letter-spacing: .4375px; + white-space: nowrap; + + .mdc-button__label { + line-height: 36px; + white-space: nowrap; + } + + &.mdc-button > .mat-icon.mat-icon { + margin: 0 0 0 -4px; + } + } + + .mat-mdc-unelevated-button:not(:disabled) { + --mat-button-filled-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); + --mdc-filled-button-container-color: var(--ai-action); + --mdc-filled-button-label-text-color: var(--ai-on-action); + padding: 0 16px; + } + + .mat-mdc-unelevated-button.warn:not(:disabled) { + --mat-button-filled-container-color: var(--tb-crit); + --mdc-filled-button-container-color: var(--tb-crit); + } + + .mat-mdc-button:not(:disabled) { + --mat-button-text-label-text-color: var(--tb-ink-76); + --mdc-text-button-label-text-color: var(--tb-ink-76); + padding: 0 8px; + } + + .mat-mdc-outlined-button:not(:disabled) { + --mat-button-outlined-label-text-color: var(--tb-ink-76); + --mdc-outlined-button-label-text-color: var(--tb-ink-76); + --mat-button-outlined-outline-color: var(--k-stroke); + --mdc-outlined-button-outline-color: var(--k-stroke); + background: var(--tb-surface); + } + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } +} + +.k-deny { + margin-top: 10px; +} + +.k-deny-in { + width: 100%; + box-sizing: border-box; + height: 36px; + padding: 0 12px; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font: 400 14px/34px var(--tb-font); + color: var(--tb-ink); + + &::placeholder { + color: var(--k-faint); + } + + &:focus { + outline: 0; + border-color: var(--ai-focus); + box-shadow: 0 0 0 1px var(--ai-focus); + } +} + +@container k-chat (max-width: 560px) { + .k-fields { + grid-template-columns: minmax(0, 1fr); + gap: 1px 0; + + dt { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + dd { + margin-bottom: 6px; + + &:last-child { + margin-bottom: 0; + } + } + } + + .k-actions { + flex-wrap: wrap; + } +} + +@container k-chat (max-width: 420px) { + .k-diff { + thead { + display: none; + } + + tr { + display: block; + padding: 4px 0; + } + + tbody th { + display: block; + padding: 0; + } + + td { + display: inline; + padding: 0; + } + + .k-diff-now::before { + content: '→'; + margin: 0 12px 0 8px; + color: var(--tb-ink-38); + } + } +} + +@media (prefers-reduced-motion: reduce) { + .tb-disc > summary::before { + transition: none; + } +} From b1538077e0133e485a506eb4268643524ef1f46d Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 17:44:36 +0200 Subject: [PATCH 007/183] feat: the AI chat's turns, empty chat and code blocks follow the chat kit: day lines, the user turn with copy, edit and a fold for long pastes, sent files as rows, an empty chat anchored to the top with Start a task and the animated spark, and code blocks with a head, folding, wrap, per-command copy and the kit's highlighting in place of the markdown copy wrapper --- .../ai/ai-attachments.component.html | 31 +- .../ai/ai-attachments.component.scss | 146 +++--- .../ai/ai-chat-messages.component.html | 47 +- .../ai/ai-chat-messages.component.scss | 424 +++++++++++++++++- .../ai/ai-chat-messages.component.ts | 80 +++- .../home/components/ai/ai-chat.component.html | 21 +- .../home/components/ai/ai-chat.component.scss | 110 ++++- .../home/components/ai/ai-chat.component.ts | 6 + .../home/components/ai/ai-code-block.ts | 414 +++++++++++++++++ .../home/components/ai/ai-spark.component.ts | 119 +++++ .../components/ai/ai-work-line.component.scss | 5 +- .../modules/home/components/ai/ai.module.ts | 4 +- .../assets/locale/locale.constant-en_US.json | 28 ++ ui-ngx/src/theme/ai-theme.scss | 69 ++- 14 files changed, 1343 insertions(+), 161 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts 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 db8c319e86..b31ed860fd 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 @@ -4,27 +4,22 @@ SPDX-License-Identifier: BUSL-1.1 --> -
+
@for (item of shown; track item.resource.id) { -
+
+ + {{ item.resource.name }} + @if (!item.image && item.extension) { {{ item.extension }} · }{{ item.resource.size | fileSize }} + + }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss index cdc5f73333..0d9b0dcfcd 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 @@ -2,92 +2,84 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - max-width: 100%; - - .attachments { - display: flex; - flex-wrap: wrap; - gap: 8px; - justify-content: inherit; - } - - .attachment { - position: relative; - display: flex; - align-items: center; - border-radius: 10px; - border: 1px solid var(--k-stroke); - background: var(--tb-surface); - overflow: hidden; - flex: none; - cursor: pointer; +} - &:hover { - border-color: var(--ai-focus); - } +.k-files { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); +} - &.image { - width: 64px; - height: 64px; - justify-content: center; - background: var(--tb-line-soft); +.k-file { + display: flex; + align-items: center; + gap: 10px; + max-width: 100%; + min-width: 0; + padding: 6px 10px 6px 8px; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font: 400 13.5px/20px var(--tb-font); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + text-align: left; + cursor: pointer; - img { - width: 100%; - height: 100%; - object-fit: cover; - } + &:hover { + border-color: rgba(0, 0, 0, 0.2); + } - .placeholder { - color: var(--tb-ink-38); - } - } + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } - &.file { - gap: 8px; - height: 48px; - max-width: 220px; - padding: 0 12px 0 8px; + > .mat-icon { + flex: none; + color: var(--tb-ink-54); + } +} - .file-icon { - display: flex; - align-items: center; - justify-content: center; - flex: none; - width: 32px; - height: 32px; - border-radius: 8px; - color: var(--ai-selected-text); - background: var(--ai-selected-wash); +.k-file-pic { + flex: none; + width: 32px; + height: 32px; + overflow: hidden; + border-radius: 6px; + background: linear-gradient(135deg, #cfd8dc, #90a4ae); + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06); - mat-icon { - font-size: var(--chat-icon); - width: var(--chat-icon); - height: var(--chat-icon); - } - } + img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + } +} - .file-meta { - display: flex; - flex-direction: column; - min-width: 0; - line-height: var(--chat-meta-lh); +.k-file-text { + display: flex; + flex-direction: column; + min-width: 0; - .file-name { - font-size: var(--chat-meta); - font-weight: 500; - color: var(--tb-ink); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } + b { + max-width: 240px; + overflow: hidden; + font-size: 13.5px; + line-height: 18px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; + } - .file-info { - font-size: var(--chat-caption); - color: var(--k-faint); - white-space: nowrap; - } - } - } + small { + font-size: 12px; + line-height: 16px; + color: var(--tb-ink-76); } } 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 89c8e53f84..04caf4eb16 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 @@ -5,20 +5,43 @@ --> @for (msg of messages; track $index) { + @if (dayLines[$index]; as day) { + + } @if (msg.from === 'USER') {
- @if (msg.resources?.length) { - - } - @if (msg.content) { -
{{ msg.content }}
- } - @if (msg.time) { -
+
+ @if (msg.content) { +
{{ msg.content }}
+ @if (isFolded($index, msg.content)) { + + } + } + @if (msg.resources?.length) { + + } +
+
+ @if (msg.content) { + + + + + } + @if (msg.time) { -
- } + } +
} @else if (msg.from === 'ACTION') { @if (msg.data.status !== 'RUNNING' || $index === runningLead) { @@ -48,7 +71,7 @@ } @else {
- + @if (summaries[$index]; as entities) { } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 6c4423bc11..9cb92e3da2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -20,27 +20,57 @@ align-items: flex-end; gap: 6px; - .user-attachments { - max-width: 80%; + .turn { + display: grid; + justify-items: end; + gap: 6px; + max-width: 85%; + font-size: 14px; + line-height: 20px; - ::ng-deep .attachments { - justify-content: flex-end; + tb-ai-attachments { + margin-top: 8px; + } - .attachment.image { - width: 120px; - height: 90px; - } + @container k-chat (max-width: 599px) { + max-width: 88%; + } + + .msg { + max-width: none; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); } } + .msg .words { + display: block; + white-space: pre-line; + } + + .msg.folded .words { + display: block; + max-height: calc(6 * var(--chat-text-lh)); + overflow: hidden; + mask-image: linear-gradient(to bottom, #000 calc(100% - var(--chat-text-lh)), transparent); + } + + .show-all { + margin: 0; + } + .msg { max-width: 85%; padding: 12px 16px; border-radius: 16px 16px 4px 16px; background: var(--ai-person); overflow: hidden; - white-space: pre-line; overflow-wrap: anywhere; + + @container k-chat (max-width: 599px) { + max-width: 88%; + padding: 10px 14px; + } color: var(--tb-ink); } } @@ -57,7 +87,7 @@ font-variant-numeric: tabular-nums; &.agent-foot { - margin-top: 4px; + margin-top: 0; } time { @@ -81,6 +111,32 @@ } } + .user-foot { + justify-content: flex-end; + + time { + order: 2; + } + } + + .k-day { + display: flex; + align-items: center; + gap: 12px; + font-size: 12px; + line-height: 16px; + letter-spacing: .25px; + color: var(--tb-ink-54); + + &::before, &::after { + content: ''; + flex: 1 1 0%; + height: 1px; + background: var(--tb-line); + } + } + + .user:hover .foot-tools, .user:focus-within .foot-tools, .ai:hover .foot-tools, .ai:focus-within .foot-tools { opacity: 1; } @@ -207,6 +263,10 @@ } + .user .msg-foot time { + margin: 0 0 0 6px; + } + &::ng-deep .ai .agent-body .tb-markdown-view { font-family: var(--tb-font); font-size: var(--chat-text); @@ -232,7 +292,7 @@ margin: 0; } - > * + * { + > * + *, > * + p { margin-top: 14px; } @@ -272,6 +332,8 @@ } code:not([class*=language-]) { + display: inline-block; + white-space: nowrap; padding: 2px 7px; border-radius: 5px; background: rgba(0, 0, 0, 0.06); @@ -347,30 +409,348 @@ margin-top: 14px; } - pre, pre[class*=language-] { + .tb-codeblock { + position: relative; + min-width: 0; + font-size: 14px; + line-height: 20px; + border-radius: 10px; + background: var(--tb-code-bg); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + + &.folded { + .tb-code { + display: none; + } + + .tb-codeblock-head { + border-bottom-color: transparent; + } + } + + &:not(.labeled) .tb-code { + padding-right: 44px; + } + + &.labeled .tb-code { + border-radius: 0 0 10px 10px; + } + + &:is([data-lang="python"], [data-lang="js"], [data-lang="c"], [data-lang="json"], [data-lang="yaml"]) .tb-code { + &, code { + white-space: pre; + overflow-wrap: normal; + } + overflow-x: auto; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.2) transparent; + } + + &.wrap .tb-code { + &, code { + white-space: pre-wrap; + overflow-wrap: anywhere; + } + } + } + + .tb-codeblock-head { + display: flex; + align-items: center; + gap: 8px; + height: 36px; + box-sizing: border-box; + padding: 0 4px 0 12px; + border-bottom: 1px solid var(--tb-code-line); + font-family: var(--tb-font); + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + font-weight: 500; + color: var(--tb-code-head-fg); + + .mat-icon { + flex: none; + color: rgba(255, 255, 255, 0.42); + } + + > .tb-codeblock-label { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + color: var(--tb-code-head-fg); + } + } + + .tb-codefold { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + height: 100%; + margin-left: -6px; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: none; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-align: left; + cursor: pointer; + + &:hover { + background: rgba(255, 255, 255, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: -2px; + } + + .tb-codeblock-label { + flex: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .tb-codeblock-size { + flex: none; + color: rgba(255, 255, 255, 0.55); + font-weight: 400; + white-space: nowrap; + } + + .tb-codefold-tg { + margin-left: auto; + transition: transform .2s ease; + } + } + + .tb-codeblock:not(.folded) .tb-codefold-tg { + transform: rotate(180deg); + } + + .tb-codecopy { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: rgba(255, 255, 255, 0.72); + font: inherit; + letter-spacing: normal; + cursor: pointer; + outline: none; + + &:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + } + + &[aria-pressed="true"] { + background: rgba(255, 255, 255, 0.12); + color: #fff; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } + + &.floating { + position: absolute; + top: 8px; + right: 8px; + } + + &::after { + content: attr(data-tip); + position: absolute; + right: 0; + bottom: calc(100% + 6px); + padding: 3px 8px; + border-radius: 5px; + background: #10181d; + color: #fff; + font: 500 11px/16px var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + box-shadow: 0 2px 8px rgba(16, 24, 40, 0.3); + opacity: 0; + pointer-events: none; + transition: opacity .12s ease; + } + + &.copied::after { + content: attr(data-copied); + } + + &:hover::after, &:focus-visible::after, &.copied::after { + opacity: 1; + } + } + + pre.tb-code, pre.tb-code[class*=language-] { margin: 0; padding: 12px 16px 14px; border: 0; border-radius: 10px; - background: var(--tb-code-bg, #1d2830); - box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + background: none; + box-shadow: none; font-family: var(--tb-mono); - font-size: 13px; - line-height: 20px; - color: #dfe7ec; + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + color: var(--tb-code-fg); white-space: pre-wrap; + overflow-wrap: anywhere; + -webkit-font-smoothing: antialiased; code, code[class*=language-] { - white-space: pre-wrap; + display: block; + white-space: inherit; + overflow-wrap: inherit; padding: 0; + border: 0; + border-radius: 0; background: none; - font-family: var(--tb-mono); - font-size: 13px; - line-height: 20px; - color: #dfe7ec; + font: inherit; + color: inherit; text-shadow: none; } } + + .tb-line { + display: block; + min-height: 20px; + + &.add, &.del { + margin: 0 -16px; + padding: 0 16px; + } + + &.add { + background: rgba(143, 227, 211, 0.12); + color: var(--hl-cmd); + } + + &.del { + background: rgba(255, 157, 146, 0.12); + color: var(--hl-err); + } + } + + .tb-codeblock.shell .tb-line { + padding-left: 24px; + text-indent: -24px; + + &.cont { + padding-left: 40px; + } + } + + pre.tb-code div.tb-cmd { + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + .tb-cmd { + position: relative; + margin: 0 -8px; + padding: 2px 36px 2px 8px; + border-radius: 6px; + + & + .tb-cmd { + margin-top: 4px; + } + + &:hover, &:focus-within { + background: rgba(255, 255, 255, 0.05); + + .tb-cmdcopy { + opacity: 1; + } + } + } + + .tb-codecopy.tb-cmdcopy { + position: absolute; + top: 0; + right: 4px; + width: 24px; + height: 24px; + opacity: 0; + text-indent: 0; + + &.copied { + opacity: 1; + } + } + + @media (hover: none) { + .tb-codecopy.tb-cmdcopy { + opacity: .6; + } + } + + .hl-cmd, .hl-ok { + color: var(--hl-cmd); + } + + .hl-flag { + color: var(--hl-flag); + } + + .hl-str, .hl-warn { + color: var(--hl-str); + } + + .hl-num, .hl-kw { + color: var(--hl-num); + } + + .hl-key, .hl-var { + color: var(--hl-key); + } + + .hl-com, .hl-op { + color: var(--hl-com); + } + + .hl-err { + color: var(--hl-err); + } + + .hl-val { + color: var(--tb-code-fg); + } + + .hl-fn { + color: var(--hl-fn); + } + + .hl-bool { + color: var(--hl-bool); + } + + .hl-lvl { + color: var(--hl-lvl); + } } } } 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 9c1e922709..116b3b3499 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 @@ -3,9 +3,11 @@ import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; import { ClipboardService } from 'ngx-clipboard'; +import { TranslateService } from '@ngx-translate/core'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; import { AiWorkState } from '@home/components/ai/ai-action.models'; import { EntityId } from '@shared/models/id/entity-id'; +import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; @Component({ selector: 'tb-ai-chat-messages', @@ -27,6 +29,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() work: AiWorkState | undefined; @Output() approvalAction = new EventEmitter(); @Output() askAgain = new EventEmitter(); + @Output() editMessage = new EventEmitter(); @Output() resourceError = new EventEmitter(); waitApproval = false; @@ -39,8 +42,16 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { summaries: Record = {}; + dayLines: Record = {}; + + private unfolded = new Set(); + + private dayTimer: ReturnType; + private static readonly PIN_TO_BOTTOM_MS = 1500; private static readonly COPIED_MS = 1200; + private static readonly FOLD_LINES = 6; + private static readonly FOLD_CHARS = 600; private releaseBottom: () => void; @@ -51,7 +62,28 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { private copiedTimeout: ReturnType; constructor(private elementRef: ElementRef, - private clipboard: ClipboardService) {} + private clipboard: ClipboardService, + private translate: TranslateService) {} + + copyText(text: string, index: number): void { + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => this.copiedIndex = -1, AiChatMessagesComponent.COPIED_MS); + } + } + + decorateCode(answer: HTMLElement): void { + decorateCodeBlocks(answer, this.translate, text => this.clipboard.copyFromContent(text)); + } + + isFolded(index: number, content: string): boolean { + return !this.unfolded.has(index) && (content.split('\n').length > AiChatMessagesComponent.FOLD_LINES || content.length > AiChatMessagesComponent.FOLD_CHARS); + } + + unfold(index: number): void { + this.unfolded.add(index); + } copyAnswer(answer: HTMLElement, index: number): void { const text = (answer.querySelector('tb-markdown') ?? answer).innerText.trim(); @@ -88,6 +120,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { setTimeout(() => this.scrollToBottom('smooth'), 0); } } + if (changes.messages) { + this.refreshDayLines(); + } if (changes.messages || changes.completedExecutions || changes.loading) { this.summaries = this.findSummaries(); } @@ -144,6 +179,48 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { this.approvalAction.emit($event); } + private refreshDayLines(): void { + const lines: Record = {}; + let previous: string | undefined; + let first = true; + this.messages.forEach((message, index) => { + const time = (message as {time?: number}).time; + if (!time) { + return; + } + const day = new Date(time).toDateString(); + if (!first && day !== previous) { + lines[index] = this.dayLabel(time); + } + previous = day; + first = false; + }); + this.dayLines = lines; + clearTimeout(this.dayTimer); + const midnight = new Date(); + midnight.setHours(24, 0, 1, 0); + this.dayTimer = setTimeout(() => this.refreshDayLines(), midnight.getTime() - Date.now()); + } + + private dayLabel(time: number): string { + const date = new Date(time); + const today = new Date(); + today.setHours(0, 0, 0, 0); + const day = new Date(date); + day.setHours(0, 0, 0, 0); + const days = Math.round((today.getTime() - day.getTime()) / 86_400_000); + if (days === 0) { + return this.translate.instant('ai-assistant.today'); + } + if (days === 1) { + return this.translate.instant('ai-assistant.yesterday'); + } + const options: Intl.DateTimeFormatOptions = days > 1 && days <= 6 + ? {weekday: 'long', day: 'numeric', month: 'long'} + : date.getFullYear() === today.getFullYear() ? {day: 'numeric', month: 'long'} : {day: 'numeric', month: 'long', year: 'numeric'}; + return new Intl.DateTimeFormat(this.translate.currentLang?.replace('_', '-') || undefined, options).format(date).replace(',', ''); + } + private findSummaries(): Record { const summaries: Record = {}; let entities: EntityId[] = []; @@ -196,6 +273,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { ngOnDestroy(): void { clearTimeout(this.copiedTimeout); + clearTimeout(this.dayTimer); this.releaseBottom?.(); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index ce8e47639e..6b3031e96e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -81,13 +81,12 @@ [denyReasons]="denyReasons()" [work]="work()" (approvalAction)="onApprovalAction($event)" - (askAgain)="onAskAgain()"> + (askAgain)="onAskAgain()" + (editMessage)="promptInput?.setValue($event)"> } @else if (!chatId()) {
- +

{{ 'ai-assistant.what-to-work-on' | translate }}

} @@ -118,6 +117,20 @@ (messageSent)="sendMsgFromUser($event)">
+ @if (!chatId() && !messages().length && !loading()) { +
+

{{ 'ai-assistant.start-a-task' | translate }}

+
+ @for (task of tasks; track task) { + + } +
+
+ }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss index 6288517266..056a928358 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -254,8 +254,9 @@ container: k-chat / inline-size; &.empty { - justify-content: center; - padding-bottom: 12vh; + justify-content: flex-start; + padding-top: 64px; + padding-bottom: 24px; } } @@ -283,7 +284,7 @@ display: flex; flex-direction: column; align-items: center; - gap: 14px; + gap: 12px; text-align: center; } @@ -402,6 +403,109 @@ } } +.ai-sec { + width: 100%; + max-width: 680px; + margin-top: 16px; + text-align: left; +} + +.ai-sec-head h2 { + margin: 0; + font: 500 14px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-text-secondary); +} + +.ai-tasks { + margin-top: 8px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); +} + +.ai-task { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 20px; + align-items: center; + gap: 12px; + width: 100%; + min-height: 44px; + padding: 0 10px 0 16px; + border: 0; + background: none; + font: 400 14px/20px var(--tb-font); + letter-spacing: normal; + text-align: left; + color: var(--tb-ink); + cursor: pointer; + transition: background-color .12s ease; + + & + .ai-task { + border-top: 1px solid rgba(0, 0, 0, 0.06); + } + + &:first-child { + border-radius: 12px 12px 0 0; + } + + &:last-child { + border-radius: 0 0 12px 12px; + } + + &:hover { + background: rgba(0, 0, 0, 0.03); + + .mat-icon { + color: var(--tb-ink); + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 0; + box-shadow: inset 0 0 0 2px var(--ai-focus); + } + + b { + min-width: 0; + overflow: hidden; + font-weight: 400; + text-overflow: ellipsis; + white-space: nowrap; + } + + small { + max-width: 280px; + overflow: hidden; + font-size: 12.5px; + line-height: 18px; + color: var(--tb-ink-76); + text-overflow: ellipsis; + white-space: nowrap; + + @media (max-width: 599px) { + display: none; + } + } + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-38); + transition: transform .15s ease, color .15s ease; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + + .mat-icon { + transition: none; + } + } +} + .ai-chat-body.empty .ai-chat-composer { position: static; max-width: 680px; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 3134f3fdc5..f7f928e351 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -112,6 +112,8 @@ export class AiChatComponent implements OnInit, OnDestroy { work = signal(undefined); + readonly tasks = ['connect-device', 'build-dashboard', 'set-up-alarm']; + scrolled = signal(false); private atEnd = signal(true); @@ -342,6 +344,10 @@ export class AiChatComponent implements OnInit, OnDestroy { this.aiChat.resolveToolApproval(result, {ignoreLoading: true, ignoreErrors: true}).subscribe(); } + startTask(task: string): void { + this.promptInput?.setValue(this.translate.instant('ai-assistant.task.' + task + '.prompt')); + } + onAskAgain(): void { if (!this.loading()) { this.sendMsgFromUser({message: this.translate.instant('ai-assistant.review.ask-again-message'), resources: []}); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts new file mode 100644 index 0000000000..2787b16fac --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -0,0 +1,414 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; + +interface CodeLanguage { + lang: string; + label: string; + icon: string; +} + +const FOLD_LINES = 10; +const LONG_LINE = 72; +const COPIED_MS = 1500; +const SIDEWAYS = ['python', 'js', 'c', 'json', 'yaml']; + +const LANGUAGES: Record = { + bash: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + sh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + shell: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + zsh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + console: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + powershell: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + ps1: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + json: {lang: 'json', label: 'JSON', icon: 'data_object'}, + yaml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + yml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + log: {lang: 'log', label: 'Log', icon: 'notes'}, + diff: {lang: 'diff', label: 'Diff', icon: 'difference'}, + patch: {lang: 'diff', label: 'Diff', icon: 'difference'}, + js: {lang: 'js', label: 'JavaScript', icon: 'code'}, + javascript: {lang: 'js', label: 'JavaScript', icon: 'code'}, + ts: {lang: 'js', label: 'TypeScript', icon: 'code'}, + typescript: {lang: 'js', label: 'TypeScript', icon: 'code'}, + tbel: {lang: 'js', label: 'TBEL', icon: 'code'}, + python: {lang: 'python', label: 'Python', icon: 'code'}, + py: {lang: 'python', label: 'Python', icon: 'code'}, + c: {lang: 'c', label: 'C', icon: 'code'}, + cpp: {lang: 'c', label: 'C++', icon: 'code'}, + arduino: {lang: 'c', label: 'Arduino', icon: 'code'}, + java: {lang: 'c', label: 'Java', icon: 'code'}, + sql: {lang: 'text', label: 'SQL', icon: 'code'}, + xml: {lang: 'text', label: 'XML', icon: 'code'}, + html: {lang: 'text', label: 'HTML', icon: 'code'}, + css: {lang: 'text', label: 'CSS', icon: 'code'} +}; + +export function decorateCodeBlocks(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + root.querySelectorAll('pre').forEach(pre => { + if (!pre.closest('.tb-codeblock')) { + decorate(pre, translate, copy); + } + }); +} + +function languageOf(pre: HTMLElement): CodeLanguage | null { + const classes = [pre.className, pre.querySelector('code')?.className ?? ''].join(' '); + const name = /(?:^|\s)language-([\w+#-]+)/.exec(classes)?.[1]?.toLowerCase(); + if (!name || name === 'text' || name === 'plaintext' || name === 'none') { + return null; + } + return LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; +} + +function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const text = (pre.textContent ?? '').replace(/\n$/, ''); + const language = languageOf(pre); + const lang = language?.lang ?? 'text'; + const shell = lang === 'shell' || lang === 'powershell'; + const commands = shell ? splitCommands(text) : [text]; + const code = element('code', 'lang-' + lang); + if (commands.length > 1) { + code.append(...commands.map(command => { + const row = element('div', 'tb-cmd'); + row.append(...lines(lang, command), commandCopyBtn(command, translate, copy)); + return row; + })); + } else { + code.append(...lines(lang, text)); + } + pre.className = 'tb-code'; + pre.replaceChildren(code); + const lineCount = text.split('\n').length; + const folds = lineCount > FOLD_LINES; + const block = element('div', 'tb-codeblock'); + const wrapper = pre.closest('.code-wrapper'); + if (wrapper) { + wrapper.parentNode.insertBefore(pre, wrapper); + wrapper.remove(); + } + block.dataset.lang = lang; + block.classList.toggle('shell', shell); + block.classList.toggle('labeled', !!language || folds); + block.classList.toggle('folds', folds); + block.classList.toggle('folded', folds); + pre.parentNode.insertBefore(block, pre); + const copyButton = copyBtn(text, translate, copy); + if (language || folds) { + const head = element('div', 'tb-codeblock-head'); + const label = element('span', 'tb-codeblock-label'); + label.textContent = language?.label ?? translate.instant('ai-assistant.code.script'); + if (folds) { + const toggle = element('button', 'tb-codefold') as HTMLButtonElement; + toggle.type = 'button'; + toggle.setAttribute('aria-expanded', 'false'); + const size = element('span', 'tb-codeblock-size'); + size.textContent = translate.instant('ai-assistant.code.lines', {count: lineCount}); + toggle.append(...[language ? icon(language.icon, 'tb-mat-16') : null, label, size, icon('expand_more', 'tb-mat-18 tb-codefold-tg')].filter(Boolean)); + toggle.addEventListener('click', () => { + const open = block.classList.toggle('folded') === false; + toggle.setAttribute('aria-expanded', String(open)); + }); + head.append(toggle); + } else { + head.append(icon(language.icon, 'tb-mat-16'), label); + } + const wrap = wrapBtn(block, text, translate); + head.append(...[wrap, copyButton].filter(Boolean)); + block.append(head, pre); + } else { + copyButton.classList.add('floating'); + block.append(pre, copyButton); + } +} + +function wrapBtn(block: HTMLElement, text: string, translate: TranslateService): HTMLButtonElement | null { + if (!SIDEWAYS.includes(block.dataset.lang) || !text.split('\n').some(line => line.length > LONG_LINE)) { + return null; + } + const button = element('button', 'tb-codecopy tb-wrap') as HTMLButtonElement; + button.type = 'button'; + const tip = (on: boolean) => translate.instant(on ? 'ai-assistant.code.one-line-each' : 'ai-assistant.code.wrap-lines'); + button.dataset.tip = tip(false); + button.setAttribute('aria-label', translate.instant('ai-assistant.code.wrap-long-lines')); + button.setAttribute('aria-pressed', 'false'); + button.append(icon('wrap_text', 'tb-mat-16')); + button.addEventListener('click', () => { + const on = block.classList.toggle('wrap'); + button.setAttribute('aria-pressed', String(on)); + button.dataset.tip = tip(on); + }); + return button; +} + +function commandCopyBtn(text: string, translate: TranslateService, copy: (text: string) => boolean): HTMLButtonElement { + const button = copyBtn(text, translate, copy); + button.classList.add('tb-cmdcopy'); + return button; +} + +function copyBtn(text: string, translate: TranslateService, copy: (text: string) => boolean): HTMLButtonElement { + const button = element('button', 'tb-codecopy') as HTMLButtonElement; + button.type = 'button'; + button.dataset.tip = translate.instant('ai-assistant.copy'); + button.dataset.copied = translate.instant('ai-assistant.copied'); + button.setAttribute('aria-label', translate.instant('ai-assistant.copy')); + button.append(icon('content_copy', 'tb-mat-16')); + let timer: ReturnType; + button.addEventListener('click', () => { + if (copy(text)) { + button.classList.add('copied'); + clearTimeout(timer); + timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); + } + }); + return button; +} + +function icon(name: string, size: string): HTMLElement { + const glyph = element('span', `mat-icon material-icons notranslate ${size}`); + glyph.setAttribute('aria-hidden', 'true'); + glyph.textContent = name; + return glyph; +} + +function element(tag: string, classes: string): HTMLElement { + const created = document.createElement(tag); + created.className = classes; + return created; +} + +type Piece = string | HTMLElement | null; + +interface ShellState { + command: boolean; + quote: string | null; +} + +const KEYWORDS: Record = { + python: /^(import|from|as|def|return|if|else|elif|for|in|while|with|try|except|True|False|None|and|or|not|print)$/, + js: /^(const|let|var|await|async|function|return|if|else|for|of|new|true|false|null|import|from|export)$/, + c: /^(constexpr|const|char|int|uint16_t|uint32_t|bool|void|return|if|else|define|include|true|false)$/ +}; + +function splitCommands(text: string): string[] { + const groups: string[][] = []; + let quote: string | null = null; + let continued = false; + text.split('\n').forEach(line => { + if (!groups.length || (!quote && !continued)) { + groups.push([]); + } + groups[groups.length - 1].push(line); + quote = openQuoteAfter(line, quote); + continued = !quote && /\\\s*$/.test(line); + }); + return groups.map(group => group.join('\n')); +} + +function openQuoteAfter(line: string, quote: string | null): string | null { + for (let i = 0; i < line.length; i++) { + const char = line[i]; + if (quote) { + if (char === '\\' && quote === '"') { + i++; + } else if (char === quote) { + quote = null; + } + } else if (char === '\\') { + i++; + } else if (char === '#' && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (char === '"' || char === '\'') { + quote = char; + } + } + return quote; +} + +function lines(lang: string, text: string): HTMLElement[] { + const state: ShellState = {command: true, quote: null}; + const highlight = lineHighlighter(lang, state); + return text.split('\n').map((line, i, all) => { + let classes = 'tb-line'; + if (i && /\\\s*$/.test(all[i - 1])) { + classes += ' cont'; + } + if (lang === 'diff') { + classes += /^\+(?!\+\+ )/.test(line) ? ' add' : /^-(?!-- )/.test(line) ? ' del' : ''; + } + const span = element('span', classes); + span.append(...highlight(line).filter(piece => piece !== null && piece !== '')); + return span; + }); +} + +function lineHighlighter(lang: string, state: ShellState): (line: string) => Piece[] { + switch (lang) { + case 'shell': + case 'powershell': + return line => shellLine(line, state); + case 'json': + return jsonLine; + case 'yaml': + return yamlLine; + case 'log': + return logLine; + case 'diff': + return line => /^(\+\+\+ |--- |@@)/.test(line) ? [token('com', line)] : [line]; + case 'python': + case 'js': + case 'c': + return line => codeLine(lang, line); + default: + return line => [line]; + } +} + +function token(kind: string | null, text: string): Piece { + if (!kind) { + return text; + } + const span = element('span', 'hl-' + kind); + span.textContent = text; + return span; +} + +function shellLine(line: string, state: ShellState): Piece[] { + if (state.quote) { + const close = closingQuote(line, state.quote); + if (close < 0) { + return [token('str', line)]; + } + state.quote = null; + state.command = false; + return [token('str', line.slice(0, close + 1)), ...shellLine(line.slice(close + 1), state)]; + } + if (/^\s*#/.test(line)) { + state.command = true; + return [token('com', line)]; + } + const out: Piece[] = []; + (line.match(/"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g) || []).forEach(word => { + if (/^\s+$/.test(word)) { + out.push(word); + return; + } + if (/^(&&|\|\||\||;|&)$/.test(word)) { + state.command = true; + out.push(token('op', word)); + return; + } + if (word === '\\') { + out.push(token('op', word)); + return; + } + if (/^["']/.test(word)) { + state.command = false; + if (word.length === 1 || !word.endsWith(word[0])) { + state.quote = word[0]; + } + out.push(token('str', word)); + return; + } + if (state.command && /^[A-Za-z_]\w*=/.test(word)) { + out.push(token('var', word)); + return; + } + const kind = state.command ? 'cmd' : /^--?[A-Za-z]/.test(word) ? 'flag' : /^https?:\/\//.test(word) ? 'str' + : /^\$/.test(word) ? 'var' : /^\d+(\.\d+)?$/.test(word) ? 'num' : null; + state.command = false; + out.push(token(kind, word)); + }); + if (!state.quote && !/\\\s*$/.test(line)) { + state.command = true; + } + return out; +} + +function closingQuote(line: string, quote: string): number { + for (let i = 0; i < line.length; i++) { + if (line[i] === '\\' && quote === '"') { + i++; + } else if (line[i] === quote) { + return i; + } + } + return -1; +} + +function codeLine(lang: string, line: string): Piece[] { + const comment = lang === 'python' ? /^(\s*)(#.*)$/ : /^(\s*)(\/\/.*)$/; + const match = line.match(comment); + if (match) { + return [match[1], token('com', match[2])]; + } + const words = new RegExp('"(?:\\\\.|[^"\\\\])*"?|\'(?:\\\\.|[^\'\\\\])*\'?|`[^`]*`?|' + + (lang === 'python' ? '#.*' : '\\/\\/.*') + '|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|.', 'g'); + return (line.match(words) || []).map((word, i, all) => { + if (/^(#|\/\/)/.test(word)) { + return token('com', word); + } + if (/^["'`]/.test(word)) { + return token('str', word); + } + if (/^\d/.test(word)) { + return token('num', word); + } + if (/^(true|false|null|undefined|True|False|None)$/.test(word)) { + return token('bool', word); + } + if (KEYWORDS[lang]?.test(word)) { + return token('kw', word); + } + if (/^[A-Za-z_$]/.test(word) && all[i + 1] === '(') { + return token('fn', word); + } + return /^[{}()[\],.:;=]$/.test(word) ? token('op', word) : word; + }); +} + +function jsonLine(line: string): Piece[] { + return (line.match(/"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g) || []).flatMap(word => { + if (/^".*:$/.test(word.replace(/\s/g, ''))) { + return [token('key', word.replace(/\s*:$/, '')), token('op', word.match(/\s*:$/)[0])]; + } + if (/^"/.test(word)) { + return [token('str', word)]; + } + if (/^-?\d/.test(word)) { + return [token('num', word)]; + } + if (/^(true|false|null)$/.test(word)) { + return [token('bool', word)]; + } + return [/^[{}[\],]$/.test(word) ? token('op', word) : word]; + }); +} + +function yamlValue(value: string): Piece[] { + const match = value.match(/^(\s*)(.*?)(\s+#.*)?$/); + const text = match[2]; + const kind = !text ? null : /^["']/.test(text) ? 'str' : /^(-?\d+(\.\d+)?)$/.test(text) ? 'num' + : /^(true|false|null|yes|no)$/i.test(text) ? 'bool' : /^[|>]-?$/.test(text) ? 'op' : 'val'; + return [match[1], text ? token(kind, text) : '', match[3] ? token('com', match[3]) : null]; +} + +function yamlLine(line: string): Piece[] { + if (/^\s*#/.test(line)) { + return [token('com', line)]; + } + const pair = line.match(/^(\s*)(-\s+)?([\w.\-/]+)(:)(.*)$/); + if (pair) { + return [pair[1], pair[2] ? token('op', pair[2]) : null, token('key', pair[3]), token('op', pair[4]), ...yamlValue(pair[5])]; + } + const item = line.match(/^(\s*)(-\s+)(.*)$/); + return item ? [item[1], token('op', item[2]), ...yamlValue(item[3])] : [line]; +} + +function logLine(line: string): Piece[] { + const match = line.match(/^(.*?\|\s*|\S+\s+\d\d:\d\d:\d\d\S*\s+)?(INFO|WARN(?:ING)?|ERROR|DEBUG)?(.*)$/); + const level = match[2]; + const kind = !level ? null : level === 'INFO' ? 'lvl' : level === 'DEBUG' ? 'com' : /^WARN/.test(level) ? 'warn' : 'err'; + return [match[1] ? token('com', match[1]) : null, level ? token(kind, level) : null, match[3]]; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts new file mode 100644 index 0000000000..b3aa186e5f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +type Point = [number, number]; + +interface SparkPart { + d: string; + values: string; + keyTimes: string; + keySplines: string; + begin: string; +} + +const SPARK_WAIST = 0.55; +const CYCLE_MS = 8000; +const LOW_DELAY_MS = 2000; +const STARS: Record<'big' | 'top' | 'low', [number, number, number]> = { + big: [9.1, 11.85, 6.8], + top: [17.8, 5.95, 3.6], + low: [17.8, 17.75, 3.6] +}; + +let sparkCount = 0; + +function sparkPath(cx: number, cy: number, radius: number, waist = SPARK_WAIST, tip = 0.1): string { + const format = (p: Point) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`; + const inner = radius * waist; + const tips: Point[] = [0, 1, 2, 3].map(i => { + const angle = i * 90 * Math.PI / 180; + return [cx + radius * Math.sin(angle), cy - radius * Math.cos(angle)]; + }); + const controls: Point[] = [0, 1, 2, 3].map(i => { + const angle = (i * 90 + 45) * Math.PI / 180; + const distance = 2 * inner - radius / Math.SQRT2; + return [cx + distance * Math.sin(angle), cy - distance * Math.cos(angle)]; + }); + const along = (p0: Point, c: Point, p2: Point, t: number): Point => [ + (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * c[0] + t * t * p2[0], + (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * c[1] + t * t * p2[1] + ]; + const after: Point[] = []; + const before: Point[] = []; + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + after[i] = along(tips[i], controls[i], tips[next], tip); + before[next] = along(tips[i], controls[i], tips[next], 1 - tip); + } + let d = 'M' + format(after[0]); + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + d += 'Q' + format(controls[i]) + ' ' + format(before[next]) + 'Q' + format(tips[next]) + ' ' + format(after[next]); + } + return d + 'Z'; +} + +function star(kind: keyof typeof STARS, waist?: number, tip?: number): string { + const [cx, cy, radius] = STARS[kind]; + return sparkPath(cx, cy, radius, waist, tip); +} + +function part(frames: string[], begin: number): SparkPart { + return { + d: frames[0], + values: frames.join(';'), + keyTimes: frames.map((_, i) => (i / (frames.length - 1)).toFixed(3)).join(';'), + keySplines: frames.slice(1).map(() => '0.42 0 0.58 1').join(';'), + begin: begin + 'ms' + }; +} + +@Component({ + selector: 'tb-ai-spark', + template: ` + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'ai-spark-svg', + 'aria-hidden': 'true' + } +}) +export class AiSparkComponent { + + readonly id = 'tb-ai-spark-ink-' + (++sparkCount); + + readonly fill = `url(#${this.id})`; + + readonly still = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; + + readonly parts: SparkPart[]; + + constructor() { + const phase = -(Date.now() % CYCLE_MS); + const pinch = (kind: 'top' | 'low') => [star(kind), star(kind, 0.51), star(kind), star(kind, 0.51), star(kind)]; + this.parts = [ + part([star('big'), star('big', 0.61, 0.14), star('big')], phase), + part(pinch('top'), phase), + part(pinch('low'), phase + LOW_DELAY_MS) + ]; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss index f574ba4081..906efac351 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -4,7 +4,8 @@ display: flex; align-items: flex-start; gap: 8px; - font-size: var(--chat-line); + font-family: var(--tb-mono); + font-size: 15px; line-height: var(--chat-line-lh); color: var(--tb-ink); @@ -16,6 +17,8 @@ .say { display: inline-block; min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); background: linear-gradient(90deg, var(--tb-ink-54) 0%, var(--tb-ink) 42%, var(--tb-ink-54) 58%, var(--tb-ink-54) 100%); background-size: 260% 100%; -webkit-background-clip: text; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index 9ebd6aa45e..f1c1b09a98 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -21,6 +21,7 @@ import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component' import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; import { AiRunSummaryComponent } from '@home/components/ai/ai-run-summary.component'; import { AiRecordComponent } from '@home/components/ai/ai-record.component'; +import { AiSparkComponent } from '@home/components/ai/ai-spark.component'; @NgModule({ declarations: [ @@ -41,7 +42,8 @@ import { AiRecordComponent } from '@home/components/ai/ai-record.component'; AiWorkLineComponent, AiActionLineComponent, AiRunSummaryComponent, - AiRecordComponent + AiRecordComponent, + AiSparkComponent ], imports: [ CommonModule, 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 296b4300c8..a9ebde1ba7 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -998,6 +998,34 @@ "result": "Result" }, "go-to-end": "Go to the end", + "start-a-task": "Start a task", + "code": { + "script": "Script", + "lines": "{ count, plural, =1 {1 line} other {# lines} }", + "wrap-lines": "Wrap lines", + "one-line-each": "One line each", + "wrap-long-lines": "Wrap long lines" + }, + "task": { + "connect-device": { + "title": "Connect a device", + "hint": "A sensor, a gateway or a cloud integration", + "prompt": "Connect " + }, + "build-dashboard": { + "title": "Build a dashboard", + "hint": "From the keys a device sends", + "prompt": "Build a dashboard for " + }, + "set-up-alarm": { + "title": "Set up an alarm", + "hint": "A rule on a value, and who is told", + "prompt": "Alert me when " + } + }, + "copy": "Copy", + "edit-message": "Edit: the words back in the composer", + "show-all": "Show all", "rename-save": "Save (Enter)", "rename-discard": "Discard (Esc)", "review": { diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 8a36ead9b7..8cc70b12ec 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -44,6 +44,18 @@ --ai-hue: 180; --ai-light-mint: oklch(0.87 0.06 calc(var(--ai-hue) - 20)); --ai-light-teal: oklch(0.86 0.08 calc(var(--ai-hue) - 5)); + --ai-mark-fill: + radial-gradient(80% 80% at 16% 10%, oklch(0.995 0.008 calc(var(--ai-hue) + 5) / 0.7), transparent 62%), + radial-gradient(55% 55% at 0% 100%, color-mix(in oklab, var(--ai-light-mint) 45%, transparent), transparent 70%), + linear-gradient(135deg in oklab, oklch(0.91 0.055 calc(var(--ai-hue) - 8)) 0%, oklch(0.935 0.045 calc(var(--ai-hue) + 25)) 38%, oklch(0.915 0.04 295) 70%, oklch(0.94 0.028 70) 100%); + --ai-mark-edge: + inset -1px -1px 1px 0 oklch(1 0 0 / 0.75), + inset 0 0 0 1px oklch(0.62 0.08 var(--ai-hue) / 0.14); + --ai-mark-ink: var(--tb-ink); + --ai-mark-ink-a: oklch(0.46 0.065 calc(var(--ai-hue) - 5)); + --ai-mark-ink-b: oklch(0.27 0.025 calc(var(--ai-hue) + 25)); + --ai-mark-ink-c: oklch(0.19 0.015 295); + --ai-mark-ink-fill: linear-gradient(135deg in oklab, var(--ai-mark-ink-a) 0%, var(--ai-mark-ink-b) 50%, var(--ai-mark-ink-c) 100%); --ai-light-aqua: oklch(0.88 0.07 calc(var(--ai-hue) + 25)); --ai-light-lilac: oklch(0.84 0.06 295); --ai-light-peach: oklch(0.88 0.06 45); @@ -222,14 +234,9 @@ --tb-primary-contrast-500: #ffffff; } -@property --ai-h { - syntax: ''; - inherits: true; - initial-value: 172; -} - .tb-ai-mark { --m: 28px; + --ai-spark: .66; display: inline-flex; align-items: center; justify-content: center; @@ -237,25 +244,44 @@ width: var(--m); height: var(--m); border-radius: 38%; - background: var(--ai-icon); + background: var(--ai-mark-fill); background-size: 240% 240%; - animation: tb-ai-icon-flow 8s ease-in-out infinite alternate, tb-ai-mark-hue 6s ease-in-out infinite alternate; - - .mat-icon { - font-size: calc(var(--m) * .57); - width: calc(var(--m) * .57); - height: calc(var(--m) * .57); + box-shadow: var(--ai-mark-edge); + animation: tb-ai-icon-flow 8s ease-in-out infinite alternate; + + > .mat-icon { + font-family: 'Material Icons Round'; + font-size: calc(var(--m) * var(--ai-spark)); + width: calc(var(--m) * var(--ai-spark)); + height: calc(var(--m) * var(--ai-spark)); line-height: 1; - color: oklch(0.32 0.07 var(--ai-h)) !important; + color: var(--ai-mark-ink) !important; + background: var(--ai-mark-ink-fill); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + } + + > .ai-spark-svg { + display: block; + flex: none; + width: calc(var(--m) * var(--ai-spark)); + height: calc(var(--m) * var(--ai-spark)); + + svg { + display: block; + overflow: visible; + } } &.m24 { --m: 24px; } + &.m28 { --m: 28px; } &.m32 { --m: 32px; } - &.m44 { --m: 44px; } - &.m64 { --m: 64px; } + &.m44 { --m: 44px; --ai-spark: .74; } + &.m64 { --m: 64px; --ai-spark: .74; } &.m44, &.m64 { - box-shadow: 0 1px 2px rgb(16 24 40 / 0.06), 0 8px 24px color-mix(in oklab, var(--ai-light-teal) 26%, transparent); + box-shadow: var(--ai-mark-edge), 0 1px 2px rgb(16 24 40 / 0.06), 0 8px 24px color-mix(in oklab, var(--ai-light-teal) 26%, transparent); } @media (prefers-reduced-motion: reduce) { @@ -263,17 +289,16 @@ } } +.ai-spark-svg stop:nth-child(1) { stop-color: var(--ai-mark-ink-a); } +.ai-spark-svg stop:nth-child(2) { stop-color: var(--ai-mark-ink-b); } +.ai-spark-svg stop:nth-child(3) { stop-color: var(--ai-mark-ink-c); } + @keyframes tb-ai-icon-flow { 0% { background-position: 0% 0%; } 50% { background-position: 100% 60%; } 100% { background-position: 40% 100%; } } -@keyframes tb-ai-mark-hue { - from { --ai-h: calc(var(--ai-hue) - 8); } - to { --ai-h: calc(var(--ai-hue) + 120); } -} - .tb-ai-status-mark { flex: none; width: 12px; From c23433e3f6980832b33002ee73d7827de1b83f67 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 17:47:45 +0200 Subject: [PATCH 008/183] fix: the AI Assistant page keeps a history entry per chat opened from the list and follows the chatId query parameter on back, forward and URL changes --- .../ai-assistant/ai-assistant.component.ts | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts index c9f9d204fc..cab7733cca 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -13,6 +13,7 @@ import { ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { DomSanitizer } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { Store } from '@ngrx/store'; @@ -96,18 +97,28 @@ export class AiAssistantComponent implements OnInit, OnDestroy { private route = inject(ActivatedRoute); private host = inject>(ElementRef); + private browsing = false; + private urlEffect = effect(() => { const chatId = this.chatId() ?? null; if (this.route.snapshot.queryParamMap.get('chatId') !== chatId && this.aiChats.loaded()) { + const browsing = this.browsing; + this.browsing = false; this.router.navigate([], { relativeTo: this.route, queryParams: {chatId}, queryParamsHandling: 'merge', - replaceUrl: true + replaceUrl: !browsing }); } }); + private urlSubscription = this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(params => { + if (this.aiChats.loaded()) { + this.openFromUrl(params.get('chatId')); + } + }); + private refreshTimer = setInterval(() => { if (!document.hidden) { this.aiChats.refresh().subscribe({error: () => {}}); @@ -121,10 +132,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy { ngOnInit(): void { this.aiChats.load().subscribe({ next: chats => { - const chatId = this.route.snapshot.queryParamMap.get('chatId'); - if (chatId && chats.some(chat => chat.id === chatId)) { - this.chatId.set(chatId); - } + this.openFromUrl(this.route.snapshot.queryParamMap.get('chatId'), chats); }, error: err => this.showErrorMessage(err) }); @@ -166,12 +174,14 @@ export class AiAssistantComponent implements OnInit, OnDestroy { newChat(): void { this.settleRail(); + this.browsing = !!this.chatId(); this.chatId.set(undefined); setTimeout(() => this.chat?.focus()); } selectChat(chat: ChatInfo): void { this.settleRail(); + this.browsing = chat.id !== this.chatId(); this.chatId.set(chat.id); } @@ -215,6 +225,14 @@ export class AiAssistantComponent implements OnInit, OnDestroy { this.aiChats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); } + private openFromUrl(chatId: string | null, chats = this.aiChats.chats()): void { + const known = !!chatId && chats.some(chat => chat.id === chatId); + const next = known ? chatId : undefined; + if (next !== this.chatId()) { + this.chatId.set(next); + } + } + private setRailOpen(open: boolean): void { this.railOpen.set(open); try { From 1a740fa81cd8f2ade9c53c699d1f464bbb86d556 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 5 Nov 2026 17:57:22 +0200 Subject: [PATCH 009/183] fix: the scroll pill follows the prototype: switching chats or loading a chat's history no longer counts as new, the end counts as in view within 160px, every new item in the log is counted, and its tip says how many are new --- .../home/components/ai/ai-chat.component.html | 2 +- .../home/components/ai/ai-chat.component.ts | 16 +++++++++++++--- .../src/assets/locale/locale.constant-en_US.json | 1 + 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 6b3031e96e..3b7f89360f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -93,7 +93,7 @@
@if (pill(); as current) { +
+ } } @else {
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 116b3b3499..0ed7fbcc11 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 @@ -30,6 +30,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Output() approvalAction = new EventEmitter(); @Output() askAgain = new EventEmitter(); @Output() editMessage = new EventEmitter(); + @Output() resume = new EventEmitter(); @Output() resourceError = new EventEmitter(); waitApproval = false; @@ -264,7 +265,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { private findLastAnswerIndex(): number { for (let i = this.messages.length - 1; i >= 0; i--) { const message = this.messages[i]; - if (message.from === 'AI' && message.status !== 'INCOMPLETE') { + if (message.from === 'AI' && !message.status) { return i; } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 3b7f89360f..b31d357e05 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -40,7 +40,8 @@ @if (level(); as level) { - + {{ ('ai-assistant.status-' + level) | translate }} @@ -82,6 +83,7 @@ [work]="work()" (approvalAction)="onApprovalAction($event)" (askAgain)="onAskAgain()" + (resume)="resume()" (editMessage)="promptInput?.setValue($event)"> } @else if (!chatId()) { @@ -108,6 +110,7 @@ [dropZone]="chatArea" [pinned]="!!messages().length || loading()" [showAutoApprove]="true" + [sendWhileWorking]="true" [autoApprove]="autoApprove()" [autoApproveInChat]="!!chatId()" [stoppable]="!!chatId()" diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss index 056a928358..3a88c150b7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -156,6 +156,10 @@ color: var(--tb-ink-54); white-space: nowrap; + &.error { + color: var(--tb-crit); + } + .tb-ai-status-mark { width: 10px; height: 10px; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index c971b60086..ab26336c60 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -11,7 +11,6 @@ import { model, OnDestroy, OnInit, - SecurityContext, signal, untracked, ViewChild @@ -194,6 +193,11 @@ export class AiChatComponent implements OnInit, OnDestroy { return chat ? this.chats.levelOf(chat) : null; }); + statusTip = computed(() => { + const chat = this.chat(); + return chat ? this.chats.tipOf(chat) : ''; + }); + private openChatEffect = effect(onCleanup => { const chatId = this.chatId(); untracked(() => this.chats.setOpen(chatId, true)); @@ -367,6 +371,10 @@ export class AiChatComponent implements OnInit, OnDestroy { ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} : {from: 'USER', content: prompt.message, time: Date.now()}; this.messages.update(list => [...list, userMessage]); + if (this.loading() && this.chatId()) { + this.sendWhileWorking(prompt, userMessage); + return; + } this.sendMessage(prompt).subscribe({ error: err => { if (this.isConnectionLost(err) && this.chatId()) { @@ -399,6 +407,50 @@ export class AiChatComponent implements OnInit, OnDestroy { } } + resume(): void { + this.sendMsgFromUser({message: this.translate.instant('ai-assistant.resume'), resources: []}); + } + + private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void { + const chatId = this.chatId(); + let ownTurn = false; + this.aiChat.sendChatMessage(chatId, this.chatRequest(prompt), {ignoreLoading: true, ignoreErrors: true}).pipe( + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'messageQueued') { + return of(event); + } + if (!ownTurn && !this.loading()) { + ownTurn = true; + this.chats.clearFailure(chatId); + this.startLoading(); + } + return this.handleChatEvent(event); + }), + finalize(() => { + if (ownTurn) { + this.stopLoading(); + } + }) + ).subscribe({ + error: err => { + this.messages.update(list => list.filter(message => message !== userMessage)); + setTimeout(() => this.showErrorMessage(err), 0); + } + }); + } + + private chatRequest(prompt: AiPromptMessage): SendChatMessageRequest { + const request: SendChatMessageRequest = {message: prompt.message}; + if (prompt.resources.length) { + request.resources = prompt.resources.map(resource => resource.id); + } + if (this.clientContext()) { + request.clientContext = this.clientContext(); + } + return request; + } + private sendMessage(prompt: AiPromptMessage): Observable { this.messageCancelled = false; const startOrContinue$ = this.chatId() @@ -412,17 +464,14 @@ export class AiChatComponent implements OnInit, OnDestroy { this.chatId.set(chat.id); }) ); - const request: SendChatMessageRequest = {message: prompt.message}; - if (prompt.resources.length) { - request.resources = prompt.resources.map(resource => resource.id); - } - if (this.clientContext()) { - request.clientContext = this.clientContext(); - } + const request = this.chatRequest(prompt); this.setWork('reading-request', true); this.loading.set(true); return startOrContinue$.pipe( - tap(() => this.startLoading()), + tap(() => { + this.chats.clearFailure(this.chatId()); + this.startLoading(); + }), switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), takeUntil(this.cancelMessage$), concatMap(event => this.handleChatEvent(event)), @@ -506,7 +555,7 @@ export class AiChatComponent implements OnInit, OnDestroy { this.finishAction(event.data); break; case 'turnStopped': - this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'INCOMPLETE', time: Date.now()}]); + this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'STOPPED', time: Date.now()}]); break; case 'chatTitleGenerated': if (this.chatId() && event.data.title) { @@ -515,7 +564,9 @@ export class AiChatComponent implements OnInit, OnDestroy { break; default: if (event.event === 'error') { - this.showErrorToast(this.sanitizer.sanitize(SecurityContext.HTML, event.data?.message) ?? event.data?.message); + const message = event.data?.message || this.translate.instant('ai-assistant.run-failed'); + this.chats.setFailed(this.chatId(), message); + this.messages.update(list => [...list, {from: 'AI', content: message, status: 'INCOMPLETE', time: Date.now()}]); } } return of(event); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts index 2787b16fac..323854fa5a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -289,7 +289,7 @@ function shellLine(line: string, state: ShellState): Piece[] { return [token('com', line)]; } const out: Piece[] = []; - (line.match(/"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g) || []).forEach(word => { + matches(line, /"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g).forEach(word => { if (/^\s+$/.test(word)) { out.push(word); return; @@ -345,7 +345,7 @@ function codeLine(lang: string, line: string): Piece[] { } const words = new RegExp('"(?:\\\\.|[^"\\\\])*"?|\'(?:\\\\.|[^\'\\\\])*\'?|`[^`]*`?|' + (lang === 'python' ? '#.*' : '\\/\\/.*') + '|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|.', 'g'); - return (line.match(words) || []).map((word, i, all) => { + return matches(line, words).map((word, i, all) => { if (/^(#|\/\/)/.test(word)) { return token('com', word); } @@ -369,7 +369,7 @@ function codeLine(lang: string, line: string): Piece[] { } function jsonLine(line: string): Piece[] { - return (line.match(/"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g) || []).flatMap(word => { + return matches(line, /"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g).flatMap(word => { if (/^".*:$/.test(word.replace(/\s/g, ''))) { return [token('key', word.replace(/\s*:$/, '')), token('op', word.match(/\s*:$/)[0])]; } @@ -412,3 +412,7 @@ function logLine(line: string): Piece[] { const kind = !level ? null : level === 'INFO' ? 'lvl' : level === 'DEBUG' ? 'com' : /^WARN/.test(level) ? 'warn' : 'err'; return [match[1] ? token('com', match[1]) : null, level ? token(kind, level) : null, match[3]]; } + +function matches(line: string, pattern: RegExp): string[] { + return line.match(pattern) ?? []; +} 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 95d0670e35..24a1075364 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 @@ -93,14 +93,20 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr @Input() stopping = false; + @Input() sendWhileWorking = false; + @Output() stopped = new EventEmitter(); - get canStop(): boolean { + get working(): boolean { return this.loading && this.stoppable; } + get canStop(): boolean { + return this.working && !(this.sendWhileWorking && this.hasContent()); + } + stop(): void { - if (this.canStop && !this.stopping) { + if (this.working && !this.stopping) { this.stopped.emit(); } } @@ -139,7 +145,11 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr get canSend(): boolean { const ready = this.attachments().some(attachment => attachment.status === 'ready'); - return !this.loading && !this.uploading() && (!!this.message.value?.trim() || ready); + return (!this.loading || this.sendWhileWorking) && !this.uploading() && (!!this.message.value?.trim() || ready); + } + + private hasContent(): boolean { + return this.hasText() || this.attachments().some(attachment => attachment.status === 'ready'); } ngOnChanges(changes: SimpleChanges): void { @@ -182,7 +192,7 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } onKeydown(event: KeyboardEvent): void { - if (event.key === 'Escape' && this.canStop) { + if (event.key === 'Escape' && this.working) { event.preventDefault(); this.stop(); return; @@ -201,7 +211,7 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr send(): void { const msg = this.message.value?.trim() ?? ''; const ready = this.attachments().filter(attachment => attachment.status === 'ready'); - if (this.loading || this.uploading() || (!msg && !ready.length)) { + if ((this.loading && !this.sendWhileWorking) || this.uploading() || (!msg && !ready.length)) { return; } this.fly(); diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html index 4c09d19965..1b5194c62d 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html @@ -52,14 +52,14 @@ (keydown)="onRenameKeydown($event)" (blur)="finishRename(chat, rowTitle.value)">
} @else { -
{{ chat.title }} @if (aiChats.levelOf(chat); as level) { - + } + @if (waitItem(); as wait) { + + } } diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss index f688aa3ae9..56721bfa25 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -454,3 +454,40 @@ display: inline-flex; } } + +.ai-wait-btn .ai-wait-n { + min-width: 20px; + height: 20px; + padding: 0 6px; + box-sizing: border-box; + border-radius: 10px; + background: var(--tb-ink); + color: #fff; + font: 500 11.5px/20px var(--tb-font); + font-style: normal; + font-variant-numeric: tabular-nums; + text-align: center; +} + +.ai-wait-btn:hover .ai-wait-n { + background: #000; +} + +.ai-bar-chats .ai-badge { + position: absolute; + top: 2px; + left: 18px; + min-width: 16px; + height: 16px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 8px; + background: var(--tb-ink); + color: #fff; + font: 500 11px/16px Roboto, sans-serif; + font-style: normal; + font-variant-numeric: tabular-nums; + text-align: center; + box-shadow: 0 0 0 2px var(--tb-surface); + pointer-events: none; +} diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts index cab7733cca..b6d1bdf2a6 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -85,11 +85,35 @@ export class AiAssistantComponent implements OnInit, OnDestroy { const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4; groups[index].chats.push(chat); } - const needsFirst = (chat: ChatInfo) => this.aiChats.levelOf(chat) === 'needs' ? 0 : 1; + const needsFirst = (chat: ChatInfo) => this.aiChats.needsAttention(chat) ? 0 : 1; groups.forEach(group => group.chats.sort((a, b) => needsFirst(a) - needsFirst(b))); return groups.filter(group => group.chats.length); }); + waiting = computed(() => { + const rank = (chat: ChatInfo) => this.aiChats.levelOf(chat) === 'needs' ? 0 : 1; + return this.aiChats.chats() + .filter(chat => this.aiChats.needsAttention(chat)) + .sort((a, b) => rank(a) - rank(b) || b.createdTime - a.createdTime); + }); + + waitItem = computed<{count: number; tip: string; label: string} | null>(() => { + const waiting = this.waiting(); + if (!waiting.length || (waiting.length === 1 && waiting[0].id === this.chatId())) { + return null; + } + if (waiting.length === 1) { + const title = waiting[0].title || this.translate.instant('ai-assistant.new-chat'); + return { + count: 1, + tip: this.translate.instant('ai-assistant.waiting-one-tip', {title, status: this.aiChats.tipOf(waiting[0])}), + label: this.translate.instant('ai-assistant.waiting-one', {title}) + }; + } + const text = this.translate.instant('ai-assistant.waiting-many', {count: waiting.length}); + return {count: waiting.length, tip: text, label: text}; + }); + private translate = inject(TranslateService); private store = inject(Store); private sanitizer = inject(DomSanitizer); @@ -179,6 +203,16 @@ export class AiAssistantComponent implements OnInit, OnDestroy { setTimeout(() => this.chat?.focus()); } + openWaiting(): void { + const waiting = this.waiting(); + if (waiting.length === 1) { + this.selectChat(waiting[0]); + return; + } + this.setRailOpen(true); + setTimeout(() => this.host.nativeElement.querySelector('.ai-row.attn')?.scrollIntoView({block: 'nearest'})); + } + selectChat(chat: ChatInfo): void { this.settleRail(); this.browsing = chat.id !== this.chatId(); 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 80a734bcce..5600644263 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -16,11 +16,12 @@ export interface ChatInfo extends ChatConfiguration { createdTime: number; pinned?: boolean; status?: ChatStatus; + statusReason?: string; } -export type ChatStatus = 'RUNNING' | 'NEEDS_YOU'; +export type ChatStatus = 'RUNNING' | 'NEEDS_YOU' | 'FAILED'; -export type ChatLevel = 'needs' | 'running'; +export type ChatLevel = 'needs' | 'running' | 'error'; export interface BaseChatEvent { event: string; @@ -175,8 +176,13 @@ export enum ToolApprovalResult { TIMEOUT = 'TIMEOUT' } +export interface MessageQueuedEvent extends BaseChatEvent { + event: 'messageQueued'; + data: Record; +} + export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent - | TurnResumedEvent | TurnStoppedEvent | ToolStartedEvent | ToolFinishedEvent; + | TurnResumedEvent | TurnStoppedEvent | MessageQueuedEvent | ToolStartedEvent | ToolFinishedEvent; export enum AiAssistantViewType { DASHBOARD = 'DASHBOARD', diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 023def6d0b..8e019619bf 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -177,7 +177,7 @@ export type ChatMessage = GeneralChatMessage | ApprovalChatMessage | ActionChatM export interface GeneralChatMessage { from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE'; content: string; - status?: 'INCOMPLETE'; + status?: 'INCOMPLETE' | 'STOPPED'; resources?: AiResourceInfo[]; time?: number; } 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 2d87dd285f..46891441e9 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -998,6 +998,8 @@ "result": "Result" }, "go-to-end": "Go to the end", + "resume": "Resume", + "run-failed": "The run stopped with an error.", "new-count": "{{ count }} new", "start-a-task": "Start a task", "code": { @@ -1134,8 +1136,13 @@ "deny-placeholder": "Or say what should be different…", "status-needs": "Needs you", "status-running": "Running", + "status-error": "Failed", "status-tip-needs": "An approval waits for you", "status-tip-running": "In progress", + "status-tip-error": "The run stopped", + "waiting-one": "Open {{ title }}, it needs you", + "waiting-one-tip": "{{ title }}: {{ status }}", + "waiting-many": "{ count, plural, =1 {1 chat needs you} other {# chats need you} }", "stop": "Stop", "stopped": "You stopped this reply. Nothing more was done.", "auto-approve": "Auto-approve", From 8fbc11092c180fc328724cbfa679a50da07ab33a Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 6 Nov 2026 15:16:59 +0200 Subject: [PATCH 011/183] feat: the AI chat follows the updated kit: the working indicator on one box size, the approval's record to be made on a dotted tile with the change's verb and the approved card handing over to its action line, the summary handing over the dashboard as a media card, chips, rating and reporting an answer, Started from, the side panel rebuilt on the shared chat with the kit's docked head, width, resize, bottom sheet and full screen, and one AI Assistant button after the notifications bell replacing the pages' Configure with AI buttons --- .../services/ai-assistant-panel.service.ts | 32 +- .../src/app/core/services/ai-chats.service.ts | 6 +- .../components/ai/ai-action-line.component.ts | 16 +- .../ai/ai-approval-card.component.html | 12 +- .../ai/ai-approval-card.component.scss | 29 - .../ai/ai-approval-card.component.ts | 34 +- .../ai/ai-assistant-button.component.ts | 46 ++ .../ai/ai-assistant-panel.component.html | 126 +--- .../ai/ai-assistant-panel.component.scss | 245 ++------ .../ai/ai-assistant-panel.component.ts | 585 +++--------------- .../ai/ai-chat-messages.component.html | 46 +- .../ai/ai-chat-messages.component.scss | 44 ++ .../ai/ai-chat-messages.component.ts | 52 +- .../home/components/ai/ai-chat.component.html | 102 ++- .../home/components/ai/ai-chat.component.scss | 119 +++- .../home/components/ai/ai-chat.component.ts | 129 +++- .../ai/ai-prompt-input.component.scss | 6 +- .../components/ai/ai-run-summary.component.ts | 84 ++- .../home/components/ai/ai-spin.component.scss | 27 +- .../ai/ai-started-from.component.ts | 114 ++++ .../components/ai/ai-work-line.component.scss | 2 +- .../modules/home/components/ai/ai.module.ts | 5 + .../ai-assistant-alarm-button.component.html | 23 - .../ai-assistant-alarm-button.component.ts | 43 -- .../dashboard-page.component.html | 13 +- .../dashboard-page.component.ts | 13 +- .../entity/entities-table.component.html | 3 - .../entity/entities-table.component.ts | 8 - .../home/components/home-components.module.ts | 3 - .../send-notification-button.component.html | 29 +- .../send-notification-button.component.ts | 19 +- .../components/router-tabs.component.scss | 7 - .../src/app/modules/home/home.component.html | 12 +- .../src/app/modules/home/home.component.scss | 15 +- .../home/pages/alarm/alarm-routing.module.ts | 4 +- .../dashboard-group-config.factory.ts | 24 - .../dashboards-table-config.resolver.ts | 29 +- .../report-template-page.component.html | 1 + .../template/report-template.module.ts | 2 + .../pages/widget/widget-editor.component.html | 1 + .../pages/widget/widget-library.module.ts | 2 + .../src/app/shared/models/ai-chat.models.ts | 16 + .../shared/models/solution-creator.models.ts | 8 + .../assets/locale/locale.constant-en_US.json | 47 ++ ui-ngx/src/theme/ai-theme.scss | 342 ++++++++++ 45 files changed, 1430 insertions(+), 1095 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index efbd13bed0..2358407a9c 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts @@ -2,7 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 import { computed, DestroyRef, inject, Injectable, OnDestroy, signal } from '@angular/core'; import { Subject } from 'rxjs'; -import { distinctUntilChanged, map } from 'rxjs/operators'; +import { distinctUntilChanged, filter, map } from 'rxjs/operators'; +import { NavigationStart, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { AiAssistantPanelConfig, @@ -21,9 +22,14 @@ import { selectAuthUser } from '@core/auth/auth.selectors'; @Injectable({ providedIn: 'root' }) export class AiAssistantPanelService implements OnDestroy { + private static readonly WITHOUT_PANEL = ['/home', '/ai-assistant']; + private _open = signal(false); readonly open = this._open.asReadonly(); + private _suppressed = signal(false); + readonly suppressed = this._suppressed.asReadonly(); + private _enabled = signal(false); readonly enabled = this._enabled.asReadonly(); @@ -48,6 +54,26 @@ export class AiAssistantPanelService implements OnDestroy { private localStorage = inject(LocalStorageService); private store = inject(Store); private destroyRef = inject(DestroyRef); + private router = inject(Router); + + private routeWatch = (() => { + this._suppressed.set(AiAssistantPanelService.withoutPanel(this.router.url)); + this.router.events.pipe( + filter((event): event is NavigationStart => event instanceof NavigationStart), + takeUntilDestroyed(this.destroyRef) + ).subscribe(event => { + const suppressed = AiAssistantPanelService.withoutPanel(event.url); + this._suppressed.set(suppressed); + if (suppressed) { + this._open.set(false); + } + }); + })(); + + private static withoutPanel(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/')); + } private _autoApproveUserId: string | null = null; private _autoApproveChats = signal>(new Set()); @@ -67,9 +93,6 @@ export class AiAssistantPanelService implements OnDestroy { private _teardownTimer: NodeJS.Timeout; toggle(): void { - if (!this._enabled()) { - return; - } this._open.update(open => !open); } @@ -252,7 +275,6 @@ export class AiAssistantPanelService implements OnDestroy { this._chats.set(null); this._teardownTimer = setTimeout(() => { this._config.set(null); - this._open.set(false); }); } } diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts index d0ecd0c791..12ea0fb25d 100644 --- a/ui-ngx/src/app/core/services/ai-chats.service.ts +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -7,7 +7,7 @@ import { TranslateService } from '@ngx-translate/core'; import { AiChatService } from '@core/http/ai-chat.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { DialogService } from '@core/services/dialog.service'; -import { ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; +import { AnswerFeedback, ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; @Injectable({ providedIn: 'root' }) export class AiChatsService { @@ -134,6 +134,10 @@ export class AiChatsService { ); } + sendFeedback(chatId: string, feedback: AnswerFeedback): Observable { + return this.aiChat.updatedChat(chatId, {feedback}, {ignoreLoading: true}); + } + setPinned(chatId: string, pinned: boolean): Observable { return this.aiChat.updatedChat(chatId, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( tap(() => this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, pinned} : chat))) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index a86fff9439..eae18a3658 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -31,6 +31,10 @@ export class AiActionLineComponent { more = input(0); + outcomeText = input(); + + autoApproved = input(false); + private runWords = computed(() => this.translate.instant(this.words().key + '.run', this.words().params)); running = computed(() => this.more() > 0 @@ -38,13 +42,21 @@ export class AiActionLineComponent { : this.runWords()); outcome = computed(() => { + const words = this.outcomeWords(); + return this.autoApproved() ? this.translate.instant('ai-assistant.action.auto-approved', {words}) : words; + }); + + private outcomeWords(): string { const action = this.action(); - const words = this.words(); + if (this.outcomeText()) { + return this.outcomeText(); + } if (action.status === 'FAILURE') { return this.reason(action.result) ?? this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); } + const words = this.words(); return this.translate.instant(words.key + '.done', words.params); - }); + } duration = computed(() => this.action().durationMs !== undefined ? aiActionDuration(this.action().durationMs) : ''); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index 53724d6f5c..1aff3367bc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -4,6 +4,9 @@ SPDX-License-Identifier: BUSL-1.1 --> +@if (handedOver) { + +} @else {
{{ headText }}
@if (review) { + [class.closed]="recordClosed" [class.planned]="planned"> } @switch (state) { @case ('pending') { @@ -67,7 +70,7 @@
-@if (outcome; as result) { -
- - {{ result.text }} -
} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss index 3853f918d6..829dc96e3c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss @@ -3,32 +3,3 @@ :host { display: block; } - -.k-out { - display: flex; - align-items: flex-start; - gap: 8px; - margin-top: 10px; - font-family: var(--tb-font); - font-size: var(--chat-line); - line-height: var(--chat-line-lh); - color: var(--tb-ink); - - .k-out-mark { - flex: none; - width: 20px; - height: 22px; - font-size: 22px; - line-height: 22px; - color: var(--tb-ok); - } - - &.fail .k-out-mark { - color: var(--tb-crit); - } - - .k-out-say { - min-width: 0; - overflow-wrap: anywhere; - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index fa4b1da4b3..5fd04f92ce 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -21,6 +21,7 @@ import { ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { AiAction } from '@home/components/ai/ai-action.models'; import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; export type ApprovalCardState = 'pending' | 'approved' | 'auto' | 'denied' | 'expired'; @@ -76,6 +77,8 @@ export class AiApprovalCardComponent implements OnChanges { state: ApprovalCardState = 'pending'; + handedOver: AiAction | null = null; + private autoApproved = false; private readonly cd = inject(ChangeDetectorRef); @@ -98,6 +101,12 @@ export class AiApprovalCardComponent implements OnChanges { this.state = 'denied'; } else { this.state = this.autoApproved ? 'auto' : 'approved'; + this.handedOver = { + executionId: result.executionId, + tool: '', + status: result.executionStatus, + startedAt: this.data.time ?? Date.now() + }; } this.cd.detectChanges(); } @@ -130,13 +139,28 @@ export class AiApprovalCardComponent implements OnChanges { return this.translate.instant('ai-assistant.review.head.' + this.state); } - get outcome(): {failed: boolean; text: string} | null { + get outcomeText(): string { const result = this.completedExecution; - if (!result || result.approvalStatus !== ToolApprovalResult.APPROVED) { - return null; + const failed = result?.executionStatus !== 'SUCCESS'; + return result?.message || this.translate.instant(failed ? 'ai-assistant.error' : 'ai-assistant.approved'); + } + + get planned(): boolean { + return this.review?.change === 'CREATE'; + } + + get approveLabel(): string { + if (this.isDestructive) { + return 'ai-assistant.review.delete'; + } + switch (this.review?.change) { + case 'CREATE': + return 'ai-assistant.review.create'; + case 'UPDATE': + return 'ai-assistant.review.update'; + default: + return 'ai-assistant.approve'; } - const failed = result.executionStatus !== 'SUCCESS'; - return {failed, text: result.message || this.translate.instant(failed ? 'ai-assistant.error' : 'ai-assistant.approved')}; } get alarmRule(): boolean { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts new file mode 100644 index 0000000000..d4e638f36a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { Operation, Resource } from '@shared/models/security.models'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; + +@Component({ + selector: 'tb-ai-assistant-button', + template: ` + @if (available && !panelService.open() && !panelService.suppressed()) { + + } + `, + styles: [` + :host { + display: contents; + } + `], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiAssistantButtonComponent { + + panelService = inject(AiAssistantPanelService); + + private readonly authState = getCurrentAuthState(inject(Store)); + + readonly available = this.authState.aiEnabled + && this.authState.authUser?.authority === Authority.TENANT_ADMIN + && inject(UserPermissionsService).hasGenericPermission(Resource.AI, Operation.ALL); + + toggle($event: Event): void { + $event.stopPropagation(); + this.panelService.openPanel(); + } +} 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 c5b607e147..510047ff26 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html @@ -4,109 +4,25 @@ SPDX-License-Identifier: BUSL-1.1 --> -
-
- - - - @for (group of groupedChats(); track group.label) { -
{{ group.label | translate }}
- @for (chat of group.chats; track chat.id) { - - } - } @empty { -
{{ 'ai-assistant.no-chats' | translate }}
- } -
-
-
- - - - - - - - -
-
-
- @if (messages().length) { -
-
- - -
- } @else { -
-
-
- - - -
-
ai-assistant.main-title
-
{{ subTitle() }}
-
-
-
- } - @if (!messages().length && promptExamples().length) { -
- @for (example of promptExamples(); track example.message) { - - } -
- } -
- - + +
+ +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss index 0e5550eb38..a5534dd9ed 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss @@ -3,223 +3,92 @@ @import '../../../../../scss/constants'; :host { - width: 480px; - overflow: hidden; - transform: translateX(100%); - transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1); position: absolute; top: 0; right: 0; bottom: 0; + z-index: 20; + width: var(--tb-ai-panel-w, 364px); display: flex; flex-direction: column; - z-index: 20; + background: var(--tb-surface, #fff); + transform: translateX(100%); + transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1), box-shadow 400ms ease; - &.open { - transform: translateX(0); + &.suppressed { + visibility: hidden; + transition: none; } - .image-main-color { - color: var(--tb-primary-500); + &.open { + transform: translateX(0); + box-shadow: -1px 0 0 rgba(16, 24, 40, 0.06), -12px 0 32px rgba(16, 24, 40, 0.06); } - .ai-assistant-container { - background: #fff; - margin: 16px 16px 16px 0; - box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.2), 0 0 0 0 rgba(0, 0, 0, 0.14), 0 0 0 0 rgba(0, 0, 0, 0.12); - border: solid 1px #e0e0e0; - border-radius: 4px; - display: flex; - flex-direction: column; - // :host is a flex column, so fill its height via flex (which subtracts the card margins) - // instead of height:100% (which ignores margins and overflows the host, clipping the input). - flex: 1; - min-height: 0; - width: 464px; - overflow: hidden; - - &.fill { - margin: 0; - width: 480px; + .tb-ai-grip { + position: absolute; + top: 0; + bottom: 0; + left: -4px; + z-index: 6; + width: 8px; + cursor: ew-resize; + touch-action: none; + + &::after { + content: ''; + position: absolute; + top: 50%; + left: 2px; + width: 4px; + height: 36px; + margin-top: -18px; + border-radius: 2px; + background: var(--tb-ink-38); + opacity: 0; + transition: opacity .12s ease; } - &.details-open { - padding: 16px 16px 16px 0; + &:hover::after, &:focus-visible::after { + opacity: 1; } - } - .ai-assistant-composer { - flex: none; - } - - .ai-assistant-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px; - white-space: nowrap; + &:focus-visible { + outline: 0; + } - .chat-selector { - font-size: 16px; - min-width: 0; - max-width: 280px; - --mat-button-text-with-icon-horizontal-padding: 12px; - --mat-button-text-label-text-weight: 400; - flex: 1; + @media #{$mat-lt-lg} { + display: none; } } - .ai-assistant-content { - width: 100%; - height: 100%; - display: flex; + .ai-assistant-container { overflow: hidden; flex: 1; - padding: 0 24px 16px; - gap: 16px; + min-height: 0; + display: flex; flex-direction: column; - - .chat-messages-container { - position: relative; - display: flex; - flex: 1 1 0; - min-height: 0; - width: calc(100% + 24px); - } - - .ai-chat-messages { - padding-right: 20px; - scrollbar-gutter: stable; - } - - .example-chips { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 8px; - width: 100%; - --mat-button-outlined-label-text-color: rgba(0, 0, 0, 0.76); - --mat-button-outlined-container-height: 32px; - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.16); - --mat-button-outlined-container-shape: 20px; - - .example-chip { - background-color: #fff; - opacity: 0; - animation: exampleChipFadeIn 220ms ease-out forwards; - - &:nth-child(2) { - animation-delay: 60ms; - } - - @media (prefers-reduced-motion: reduce) { - opacity: 1; - animation: none; - } - } - } - - @keyframes exampleChipFadeIn { - from { - opacity: 0; - transform: translateY(6px); - } - to { - opacity: 1; - transform: translateY(0); - } - } } - // <= 1279px: slide-in overlay above the content (which no longer reserves space here), - // keeping the 480px card size of the normal display mode. - @media #{$mat-lt-lg} { - - .ai-assistant-container { - width: 480px; - margin: 0; - - &.fill { - width: 480px; - } - } - - .ai-assistant-content { - min-width: 0; - } - } - - // <= 599px: full-screen panel, the card fills the whole width. - @media #{$mat-xs} { - width: 100%; - - .ai-assistant-container { - margin: 0; - width: auto; - - &.fill { - width: auto; - } - - &.details-open { - padding: 8px; - } - } + .ai-assistant-chat { + flex: 1; + min-height: 0; } -} -:host::ng-deep { - .ai-assistant-header { - .chat-selector { - .mdc-button__label { - width: 100%; - text-align: start; - text-overflow: ellipsis; - overflow: hidden; - } - } + @media #{$mat-lt-lg} { + width: 364px; } -} - -::ng-deep { - .ai-chat-list-menu.mat-mdc-menu-panel { - min-width: var(--chat-menu-dynamic-width); - max-height: 65vh; - .chat-group-label { - padding: 8px 16px; - font-size: 14px; - color: rgba(0, 0, 0, 0.76); - font-weight: 500; - } - - .mat-mdc-menu-item.chat-item { - padding-left: 32px; - min-height: 32px; - --mat-menu-item-label-text-size: 14px; - --mat-menu-item-label-text-line-height: 20px; - padding-top: 4px; - padding-bottom: 4px; - - &.selected { - --mat-menu-item-label-text-color: var(--tb-primary-500); - background-color: rgba(0,0,0,0.04); - } - } - - .chat-group-empty { - padding: 16px; - text-align: center; - color: rgba(0, 0, 0, 0.54); - font-size: 14px; - line-height: 20px; - } - } + @media #{$mat-lt-md} { + top: auto; + left: 0; + width: auto; + height: 48vh; + transform: translateY(100%); - .ai-chat-action-menu { - .delete { - --mat-menu-item-icon-color: #FF5722; - --mat-menu-item-label-text-color: #FF5722; + &.open { + transform: translateY(0); + box-shadow: 0 -1px 0 rgba(16, 24, 40, 0.06), 0 -12px 32px rgba(16, 24, 40, 0.08); } } } 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 1184fffd9d..7f60d07150 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 @@ -1,55 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - Component, - computed, - DestroyRef, - effect, - ElementRef, - inject, - OnInit, - SecurityContext, - signal, - untracked, - ViewChild -} from '@angular/core'; -import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; -import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; -import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; -import { HttpErrorResponse } from '@angular/common/http'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { - AiAssistantPromptExample, - AiChatClientContext, - AiPromptMessage, - ApprovalResult, - ChatEvent, - ChatInfo, - ChatTitleGeneratedEvent, - SendChatMessageRequest, - ToolExecutionRequestedEvent, - ToolExecutionResult -} from '@shared/models/ai-chat.models'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { MatDialog } from '@angular/material/dialog'; -import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { DAY, WEEK } from '@shared/models/time/time.models'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { isEqual, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { Component, computed, effect, ElementRef, inject, signal, untracked, ViewChild } from '@angular/core'; +import { AiAssistantPromptExample } from '@shared/models/ai-chat.models'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { DomSanitizer } from '@angular/platform-browser'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; -import { MatButton } from '@angular/material/button'; -import { EntityId } from '@shared/models/id/entity-id'; - -export interface ChatGroup { - label: string; - chats: ChatInfo[]; -} +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; @Component({ selector: 'tb-ai-assistant-panel', @@ -58,513 +13,145 @@ export interface ChatGroup { standalone: false, host: { '[class.open]': 'isOpen', + '[class.suppressed]': 'panelService.suppressed()', '[attr.inert]': 'isOpen ? null : ""', '(transitionend)': 'onSlideEnd($event)' } }) -export class AiAssistantPanelComponent implements OnInit { +export class AiAssistantPanelComponent { panelService = inject(AiAssistantPanelService); - @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatComponent) chat: AiChatComponent; get isOpen() { return this.panelService.open(); } - slideDone = signal(false); + readonly defaultWidth = 364; - loading = signal(false); + readonly minWidth = 320; - isCreatingNew = signal(false); + readonly maxWidth = 480; - messages = signal([]); - - completedExecutions = signal>({}); + width = signal(this.defaultWidth); chatId = signal(undefined); - subTitle = computed(() => { - return this.panelService.config()?.subTitle ?? this.translate.instant('ai-assistant.sub-title'); - }); - - activePlaceholder = computed(() => { - const config = this.panelService.config(); - if (this.messages().length) { - return config?.followUpPromptPlaceholder ?? this.translate.instant('ai-assistant.follow-up-prompt-placeholder'); - } - return config?.initialPromptPlaceholder ?? ''; - }); + clientContext = computed(() => this.panelService.clientContext() ?? undefined); promptExamples = computed(() => this.panelService.config()?.promptExamples ?? []); - newChatAutoApprove = signal(false); - - autoApprove = computed(() => this.chatId() ? this.panelService.isAutoApprove(this.chatId()) : this.newChatAutoApprove()); - - selectedChatTitle = computed(() => { - const id = this.chatId(); - if (!id) return null; - return (this.panelService.chats() ?? []).find(c => c.id === id)?.title ?? null; - }); - - groupedChats = computed(() => { - const chats = this.panelService.chats() ?? []; - if (!chats.length) return []; - - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - const yesterday = today - DAY; - const lastWeek = today - WEEK; - - const groups: ChatGroup[] = [ - {label: 'ai-assistant.today', chats: []}, - {label: 'ai-assistant.yesterday', chats: []}, - {label: 'ai-assistant.last-7-days', chats: []}, - {label: 'ai-assistant.older', chats: []} - ]; - - for (const chat of chats) { - if (chat.createdTime >= today) { - groups[0].chats.push(chat); - } else if (chat.createdTime >= yesterday) { - groups[1].chats.push(chat); - } else if (chat.createdTime >= lastWeek) { - groups[2].chats.push(chat); - } else { - groups[3].chats.push(chat); - } - } - - return groups.filter(g => g.chats.length > 0); - }); - - private aiChat = inject(AiChatService); - private dialog = inject(DialogService); - private translate = inject(TranslateService); - private matDialog = inject(MatDialog); - private store = inject(Store); - private destroyRef = inject(DestroyRef); - private sanitizer = inject(DomSanitizer); + private chats = inject(AiChatsService); private elementRef = inject(ElementRef); - private loadChat$ = new Subject(); - private cancelMessage$ = new Subject(); - private sessionAffectedEntities: EntityId[] = []; - private messageCancelled = false; - private resumeOnOpen = false; + private static readonly WIDTH_KEY = 'tbAiPanelWidth'; - private static readonly RESUME_ATTEMPTS = 4; - private static readonly RESUME_DELAY_MS = 2000; + private lastContextKey: string | null = null; private openEffect = effect(() => { if (this.panelService.open()) { - this.dropChatFromOtherContext(); - this.loadChats(); - const chatId = untracked(() => this.chatId()); - if (this.resumeOnOpen && chatId) { - this.resumeOnOpen = false; - this.loadChat$.next(chatId); - } - } else { - this.slideDone.set(false); - this.suspendOnClose(); + untracked(() => { + this.dropChatFromOtherContext(); + this.chats.load().subscribe(() => this.selectLastChat()); + }); } }); - private lastContextKey: string | null = null; - - // Realign the open chat when the context changes in place while the panel stays open - // (e.g. switching between dashboards). List/entity toggles collapse to the same key, so they - // do not trigger this. Guarded on a non-null key to avoid reacting to teardown clearing context. private contextSwitchEffect = effect(() => { const key = this.panelService.contextKey(); if (this.panelService.open() && this.lastContextKey !== null && key !== null && key !== this.lastContextKey) { - this.reset(); - this.loadChats(); + untracked(() => { + this.chatId.set(undefined); + this.selectLastChat(); + }); } this.lastContextKey = key; }); - ngOnInit() { - this.loadChat$.pipe( - switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( - catchError(err => { - this.messages.set([]); - this.completedExecutions.set({}); - setTimeout(() => this.showErrorMessage(err), 0); - return EMPTY; - }) - )), - takeUntilDestroyed(this.destroyRef) - ).subscribe(messages => { - this.showHistory(messages); - this.resumeTurn(this.chatId()); - }); - } - - close(): void { - this.panelService.close(); - } - - // Credit subscription and focus wait for the slide so they do not stutter it. - onSlideEnd(event: TransitionEvent): void { - if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { - return; - } - this.slideDone.set(true); - this.promptInput?.focus(); - } - - onApprovalAction(event: ApprovalResult): void { - const chatId = this.chatId(); - if (event.autoApprove && chatId) { - this.panelService.setAutoApprove(chatId, true); - } - this.aiChat.resolveToolApproval( - {executionId: event.executionId, approved: event.approved}, - {ignoreLoading: true, ignoreErrors: true} - ).subscribe(); - } - - setAutoApprove(enabled: boolean): void { - const chatId = this.chatId(); - if (chatId) { - this.panelService.setAutoApprove(chatId, enabled); - } else { - this.newChatAutoApprove.set(enabled); - } - } - - setMenuWidth(triggerEl: MatButton): void { - const width = triggerEl._elementRef.nativeElement.offsetWidth; - document.documentElement.style.setProperty('--chat-menu-dynamic-width', `${width}px`); - } - - selectChat(chat: ChatInfo): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.isCreatingNew.set(false); - this.chatId.set(chat.id); - this.panelService.setLastChatId(chat.id); - this.loadChat$.next(chat.id); - } - - useExample(example: AiAssistantPromptExample): void { - this.promptInput?.setValue(example.message); - } - - sendMsgFromUser(prompt: AiPromptMessage): void { - const userMessage: ChatMessage = prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} - : {from: 'USER', content: prompt.message, time: Date.now()}; - this.messages.update(list => [...list, userMessage]); - this.sendMessage(prompt).subscribe({ - error: (err) => { - if (this.isConnectionLost(err) && this.chatId()) { - this.showErrorToast(this.translate.instant('ai-assistant.connection-lost')); - this.resumeTurn(this.chatId(), true); - return; + constructor() { + let stored = 0; + try { + stored = Number(localStorage.getItem(AiAssistantPanelComponent.WIDTH_KEY)) || 0; + } catch { + stored = 0; + } + this.setWidth(stored || this.defaultWidth); + } + + setWidth(width: number, keep = false): void { + const max = Math.min(this.maxWidth, Math.round(window.innerWidth / 2)); + const value = Math.round(Math.min(max, Math.max(this.minWidth, width))); + this.width.set(value); + document.documentElement.style.setProperty('--tb-ai-panel-w', value + 'px'); + if (keep) { + try { + if (value === this.defaultWidth) { + localStorage.removeItem(AiAssistantPanelComponent.WIDTH_KEY); + } else { + localStorage.setItem(AiAssistantPanelComponent.WIDTH_KEY, String(value)); } - this.messages.update(list => list.filter(message => message !== userMessage)); - setTimeout(() => { - this.showErrorMessage(err); - }, 0); - }, - complete: () => { - if (!this.messageCancelled && this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } - } - }); - } - - reset(createNew?: boolean): void { - this.cancelActiveMessage(); - this.isCreatingNew.set(!!createNew); - this.chatId.set(undefined); - this.messages.set([]); - } - - private cancelActiveMessage(): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.stopLoadingState(); - this.promptInput?.reset(); - } - - // Keeps the open chat so reopening shows it right away. A reply interrupted by closing keeps running on the - // server, so reopening reloads the chat and follows that reply. - private suspendOnClose(): void { - this.resumeOnOpen = this.loading(); - this.cancelActiveMessage(); - } - - private dropChatFromOtherContext(): void { - const chatId = this.chatId(); - if (chatId && chatId !== this.panelService.lastChatIdForContext()) { - this.reset(); - } - } - - renameChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - this.matDialog.open(AiRenameDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - title: this.translate.instant('ai-assistant.rename-chat-title'), - value: this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat') - } - }).afterClosed().subscribe(newTitle => { - if (newTitle && newTitle !== this.selectedChatTitle()) { - this.aiChat.updatedChat(chatId, {title: newTitle}, {ignoreLoading: true, ignoreErrors: true}).subscribe({ - next: () => { - this.panelService.updateChatTitle(chatId, newTitle); - }, - error: (err) => { - this.showErrorMessage(err); - } - }); + } catch { + return; } - }); - } - - deleteChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - const chatTitle = this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat'); - this.dialog.confirm( - this.translate.instant('ai-assistant.delete-chat-title', {name: chatTitle}), - this.translate.instant('ai-assistant.delete-chat-text'), - this.translate.instant('action.no'), - this.translate.instant('ai-assistant.delete-chat-confirm') - ).subscribe(value => { - if (value) { - this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe(() => { - this.panelService.removeChat(chatId); - this.reset(); - }); - } - }); - } - - private loadChats(): void { - const chats = this.panelService.chats(); - if (chats !== null) { - this.selectLastChat(chats); - return; } - this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).subscribe(chats => { - this.panelService.setChats(chats); - this.selectLastChat(chats); - }); } - private selectLastChat(chats: ChatInfo[]): void { - if (!this.chatId() && !this.isCreatingNew()) { - const lastId = this.panelService.lastChatIdForContext(); - const lastChat = lastId ? chats.find(c => c.id === lastId) : null; - if (lastChat) { - this.selectChat(lastChat); - } + onGripKey(event: KeyboardEvent): void { + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault(); + this.setWidth(this.width() + (event.key === 'ArrowLeft' ? 16 : -16), true); } } - private sendMessage(prompt: AiPromptMessage): Observable { - this.initLoadingState(); - this.sessionAffectedEntities = []; - this.messageCancelled = false; - - const startOrContinue$ = this.chatId() - ? of(null) - : this.aiChat.createChat({title: 'New chat'}, {ignoreLoading: true, ignoreErrors: true}).pipe( - tap(chatId => { - if (this.newChatAutoApprove()) { - this.panelService.setAutoApprove(chatId, true); - } - this.isCreatingNew.set(false); - this.chatId.set(chatId); - this.panelService.setLastChatId(chatId); - this.panelService.addChat({id: chatId, title: 'New chat', createdTime: Date.now()}); - }) - ); - - const request: SendChatMessageRequest = { - message: prompt.message, - clientContext: this.resolveClientContextToSend() + startResize(event: PointerEvent): void { + event.preventDefault(); + const grip = event.target as HTMLElement; + const startX = event.clientX; + const startWidth = this.width(); + grip.setPointerCapture(event.pointerId); + document.body.classList.add('tb-ai-resizing'); + const move = (e: PointerEvent) => this.setWidth(startWidth + (startX - e.clientX)); + const up = () => { + grip.removeEventListener('pointermove', move); + grip.removeEventListener('pointerup', up); + grip.removeEventListener('pointercancel', up); + document.body.classList.remove('tb-ai-resizing'); + this.setWidth(this.width(), true); }; - if (prompt.resources.length) { - request.resources = prompt.resources.map(resource => resource.id); - } - - return startOrContinue$.pipe( - switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), - tap(() => { - if (request.clientContext) { - this.panelService.markClientContextSent(this.chatId(), request.clientContext); - } - }), - takeUntil(this.cancelMessage$), - concatMap(chatMsg => this.handleChatEvent(chatMsg)), - finalize(() => this.stopLoadingState()) - ); + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up); + grip.addEventListener('pointercancel', up); } - private resolveClientContextToSend(): AiChatClientContext | undefined { - const currentContext = this.panelService.clientContext(); - if (!currentContext) { - return undefined; - } - const chatId = this.chatId(); - const alreadySent = chatId ? this.panelService.getSentClientContext(chatId) : undefined; - return (!chatId || !isEqual(currentContext, alreadySent)) ? currentContext : undefined; + close(): void { + this.panelService.close(); } - private showHistory(messages: ChatMessage[]): void { - const completed: Record = {}; - for (const message of messages) { - if (message.from === 'APPROVAL' && (message as ApprovalChatMessage).result) { - const result = (message as ApprovalChatMessage).result; - completed[result.executionId] = result; - } - } - this.completedExecutions.set(completed); - this.messages.set(messages); + onChatId(chatId: string | undefined): void { + this.chatId.set(chatId); + this.panelService.setLastChatId(chatId); } - // Follows the reply still running in the chat, if any: after a reload, a reopened panel or a lost connection. - // The server replays the whole reply, so what the history already shows of it is dropped first. - private resumeTurn(chatId: string, afterConnectionLoss = false): void { - if (!chatId) { + onSlideEnd(event: TransitionEvent): void { + if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { return; } - let resumed = false; - this.messageCancelled = false; - this.sessionAffectedEntities = []; - const attempt$ = timer(afterConnectionLoss ? AiAssistantPanelComponent.RESUME_DELAY_MS : 0).pipe( - tap(() => { - if (afterConnectionLoss) { - this.initLoadingState(); - } - }), - switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) - ); - attempt$.pipe( - retry({ - count: afterConnectionLoss ? AiAssistantPanelComponent.RESUME_ATTEMPTS : 0, - delay: (error, attempt) => this.isConnectionLost(error) - ? timer(attempt * AiAssistantPanelComponent.RESUME_DELAY_MS) - : throwError(() => error) - }), - takeUntil(this.cancelMessage$), - concatMap(event => { - if (event.event === 'turnResumed') { - resumed = true; - this.initLoadingState(); - this.dropRunningReply(); - return of(event); - } - return this.handleChatEvent(event); - }), - finalize(() => { - if (resumed || afterConnectionLoss) { - this.stopLoadingState(); - } - }) - ).subscribe({ - error: () => { - if (afterConnectionLoss) { - this.showErrorToast(this.translate.instant('ai-assistant.reconnect-failed')); - } - }, - complete: () => { - if (this.messageCancelled || this.chatId() !== chatId) { - return; - } - if (this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } - if (resumed || afterConnectionLoss) { - this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) - .pipe(takeUntil(this.cancelMessage$)) - .subscribe(messages => this.showHistory(messages)); - } - } - }); + this.chat?.focus(); } - private dropRunningReply(): void { - this.messages.update(list => { - const lastUser = list.map(message => message.from).lastIndexOf('USER'); - return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; - }); - } - - private isConnectionLost(error: any): boolean { - return error instanceof HttpErrorResponse && error.status === 0; - } - - private handleChatEvent(chatMsg: ChatEvent): Observable { - switch (chatMsg.event) { - case 'assistantMessage': - this.messages.update(list => [...list, {from: 'AI', content: chatMsg.data.message, time: Date.now()}]); - return of(chatMsg); - case 'toolExecutionRequested': - return this.handleToolApproval(chatMsg); - case 'toolExecutionResult': - this.completedExecutions.update(map => ({...map, [chatMsg.data.executionId]: chatMsg.data})); - if (chatMsg.data.affectedEntities?.length) { - this.sessionAffectedEntities.push(...chatMsg.data.affectedEntities); - } - return of(chatMsg); - case 'chatTitleGenerated': - this.handleChatTitleGenerated(chatMsg); - return of(chatMsg); - default: - if (chatMsg.event === 'error') { - this.showErrorToast(this.sanitizer.sanitize(SecurityContext.HTML, chatMsg.data?.message) ?? chatMsg.data?.message); - } - return of(chatMsg); - } - } - - private handleChatTitleGenerated(chatMsg: ChatTitleGeneratedEvent): void { + private dropChatFromOtherContext(): void { const chatId = this.chatId(); - const title = chatMsg.data.title; - if (!chatId || !title) return; - this.panelService.updateChatTitle(chatId, title); - } - - private handleToolApproval(chatMsg: ToolExecutionRequestedEvent): Observable { - if (!chatMsg.data.needsApproval) { - return of(chatMsg); + if (chatId && chatId !== this.panelService.lastChatIdForContext()) { + this.chatId.set(undefined); } - this.messages.update(list => [...list, {from: 'APPROVAL', data: chatMsg.data}]); - return of(chatMsg); - } - - private initLoadingState(): void { - this.loading.set(true); } - private stopLoadingState(): void { - this.loading.set(false); - } - - showErrorMessage(error: any): void { - const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; - const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; - this.showErrorToast(message); - } - - private showErrorToast(message: string): void { - this.store.dispatch(new ActionNotificationShow({ - message, - target: 'aiAssistant', - modern: true, - type: 'error', - verticalPosition: 'bottom', - horizontalPosition: 'center' - })); + private selectLastChat(): void { + if (this.chatId()) { + return; + } + const lastId = this.panelService.lastChatIdForContext(); + if (lastId && this.chats.find(lastId)) { + this.chatId.set(lastId); + } } } 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 8ac26148dd..e9513e0c23 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 @@ -9,6 +9,9 @@ } @if (msg.from === 'USER') { + @if (msg.startedFrom) { + + }
@if (msg.content) { @@ -50,7 +53,7 @@
} } @else { -
+
@if (msg.from === 'APPROVAL') { {{ copiedIndex === $index ? 'check' : 'content_copy' }} + @if (feedback) { + + + + }
+ @if (reportingIndex === $index) { +
+
{{ 'ai-assistant.feedback.what-went-wrong' | translate }}
+
+ @for (problem of problems; track problem) { + + } +
+ +

{{ 'ai-assistant.feedback.sent-with' | translate }}

+
+ + +
+
+ } }
@if (msg.from === 'APPROVAL' && denyReasonOf(msg); as reason) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 9cb92e3da2..84c3681008 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -168,6 +168,50 @@ &.done { color: var(--tb-ok); } + + &[aria-pressed="true"] { + color: var(--ai-selected); + } + + &.muted:not([aria-pressed="true"]) { + color: var(--tb-ink-38); + } + + &:disabled { + cursor: default; + background: none; + } + } + + .k-report { + display: grid; + gap: 10px; + max-width: 560px; + margin-top: 8px; + padding: 14px 16px; + border: 1px solid var(--tb-line); + border-radius: 12px; + background: var(--tb-surface); + + .k-report-t { + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + } + + .k-chips { + gap: 6px; + } + + .k-report-note { + margin: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); + } + + .k-actions { + margin-top: 0; + } } .agent { 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 0ed7fbcc11..1ef842308a 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 @@ -4,9 +4,27 @@ import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Outpu import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; import { ClipboardService } from 'ngx-clipboard'; import { TranslateService } from '@ngx-translate/core'; -import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { + ANSWER_PROBLEMS, + AnswerProblem, + AnswerRating, + ApprovalResult, + ToolExecutionRequested, + ToolExecutionResult +} from '@shared/models/ai-chat.models'; import { AiWorkState } from '@home/components/ai/ai-action.models'; import { EntityId } from '@shared/models/id/entity-id'; + +export interface AnswerRatingEvent { + index: number; + rating: AnswerRating; +} + +export interface AnswerReportEvent { + index: number; + problem: AnswerProblem; + comment?: string; +} import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; @Component({ @@ -27,6 +45,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; @Input() denyReasons: Record = {}; @Input() work: AiWorkState | undefined; + @Input() feedback = false; + @Output() rate = new EventEmitter(); + @Output() report = new EventEmitter(); @Output() approvalAction = new EventEmitter(); @Output() askAgain = new EventEmitter(); @Output() editMessage = new EventEmitter(); @@ -58,6 +79,12 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { lastAnswerIndex = -1; + readonly problems = ANSWER_PROBLEMS; + + reportingIndex = -1; + + reportProblem: AnswerProblem | null = null; + copiedIndex = -1; private copiedTimeout: ReturnType; @@ -95,6 +122,29 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } } + toggleRating(index: number, current: string | undefined, rating: 'UP' | 'DOWN'): void { + this.rate.emit({index, rating: current === rating ? 'NONE' : rating}); + } + + openReport(index: number): void { + this.reportingIndex = index; + this.reportProblem = null; + } + + closeReport(): void { + this.reportingIndex = -1; + this.reportProblem = null; + } + + sendReport(index: number, comment: string): void { + if (!this.reportProblem) { + return; + } + const words = comment.trim(); + this.report.emit(words ? {index, problem: this.reportProblem, comment: words} : {index, problem: this.reportProblem}); + this.closeReport(); + } + fullTime(time: number): string { const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; const text = new Intl.DateTimeFormat(undefined, { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index b31d357e05..b153ba77ca 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -58,7 +58,25 @@ {{ fullscreen() ? 'fullscreen_exit' : 'fullscreen' }} } - @if (chat() && !renaming()) { + @if (variant() === 'panel') { + @if (!renaming()) { + + + @if (!fullscreen()) { + + } + } + } @else if (chat() && !renaming()) { + } +
+ } +
} @else if (!chatId()) {
- -

{{ 'ai-assistant.what-to-work-on' | translate }}

+ + @if (variant() === 'panel') { +

{{ startTitle() || ('ai-assistant.panel-title' | translate) }}

+

{{ startLine() || ('ai-assistant.panel-line' | translate) }}

+ } @else { +

{{ 'ai-assistant.what-to-work-on' | translate }}

+ }
}
@@ -105,6 +148,7 @@ }
- @if (!chatId() && !messages().length && !loading()) { + @if (variant() === 'panel' && !docked() && !chatId() && !messages().length && !loading() && prompts().length) { +
+
+ @for (example of prompts(); track example.message) { + + } +
+
+ } + @if (variant() === 'page' && !chatId() && !messages().length && !loading()) {

{{ 'ai-assistant.start-a-task' | translate }}

@@ -136,6 +193,43 @@ }
+ + @if (chat()) { + + + } + @if (recentChats().length) { +
{{ 'ai-assistant.recent-chats' | translate }}
+ @for (other of recentChats(); track other.id) { + + } + } + + @if (chat()) { + + } +
+ - -
-} diff --git a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts b/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts deleted file mode 100644 index 731caf5423..0000000000 --- a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, OnInit } from '@angular/core'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { AuthUser } from '@shared/models/user.model'; -import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { Operation, Resource } from '@shared/models/security.models'; -import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { alarmRuleEntityTypeList } from '@shared/models/alarm-rule.models'; - -@Component({ - selector: 'tb-ai-assistant-alarm-button', - templateUrl: './ai-assistant-alarm-button.component.html', - standalone: false -}) -export class AiAssistantAlarmButtonComponent implements OnInit { - - private authUser: AuthUser = getCurrentAuthUser(this.store); - private hasPermission: boolean; - - constructor(private store: Store, - private panelService: AiAssistantPanelService, - private userPermissionsService: UserPermissionsService) { - } - - ngOnInit(): void { - this.hasPermission = getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - alarmRuleEntityTypeList.some(entityType => - this.userPermissionsService.hasGenericPermissionByEntityGroupType(Operation.READ_CALCULATED_FIELD, entityType)); - } - - show(): boolean { - return this.hasPermission && !this.panelService.open(); - } - - toggleAiAssistant($event: Event): void { - $event?.stopPropagation(); - this.panelService.toggle(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html index c798ac713f..fac1ee63c3 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html @@ -66,6 +66,7 @@ } @else { @if (!isPublicUser()) { + }
@if (!isEdit && !isPublicUser()) { + } } - @if (showConfigureWithAi) { - - - } @if (isEdit) { } - @if (aiEnabled && entitiesTableConfig.aiAssistantConfig) { - - } @for (buttonDescriptor of entitiesTableConfig.headerButtonDescriptors; track buttonDescriptor.name) { } diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 05f6608ae5..43542b26fb 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -110,10 +110,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa isDetailsOpen = false; detailsPanelOpened = new EventEmitter(); - get isAiAssistantOpen() { return this.panelService.open(); } aiEnabled = getCurrentAuthState(this.store).aiEnabled; - configureWithAiButton: HeaderActionDescriptor; replaceComponent: Type; @@ -224,12 +222,6 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa if (aiConfig) { this.panelService.setEnabled(true); this.panelService.setConfig(aiConfig); - this.configureWithAiButton = { - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => this.aiEnabled && aiConfig.showButton !== false && !this.isAiAssistantOpen, - onAction: ($event) => this.toggleAiAssistant($event) - }; this.updateAiClientContext(); this.aiUpdatedData$?.unsubscribe(); if (entitiesTableConfig.entityType) { diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index 2093a762d4..6ac875c08d 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -225,7 +225,6 @@ import { AlarmAssigneePanelComponent } from '@home/components/alarm/alarm-assign import { RouterTabsComponent } from '@home/components/router-tabs.component'; import { AllEntitiesTableConfigService } from '@home/components/entity/all-entities-table-config.service'; import { SendNotificationButtonComponent } from '@home/components/notification/send-notification-button.component'; -import { AiAssistantAlarmButtonComponent } from '@home/components/alarm/ai-assistant-alarm-button.component'; import { GroupEntityInfoComponent } from '@home/components/group/group-entity-info.component'; import { ManageOwnerAndGroupsDialogComponent } from '@home/components/group/manage-owner-and-groups-dialog.component'; import { OwnerAndGroupsComponent } from '@home/components/group/owner-and-groups.component'; @@ -447,7 +446,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack ConverterTestDialogComponent, UpdatedPayloadPanelComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, ConverterLibraryComponent, @@ -639,7 +637,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack RateLimitsTextComponent, IntegrationWizardDialogComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, CancelTaskDialogComponent, diff --git a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html index 1614b4a7e8..8e685ff34e 100644 --- a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html +++ b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html @@ -5,27 +5,14 @@ SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --> -@if (showAiAssistant() || show()) { +@if (show()) {
- @if (showAiAssistant()) { - - - } - @if (show()) { - - - } + +
} diff --git a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts index ea0b547cdf..33a76e0e8a 100644 --- a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts +++ b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts @@ -15,10 +15,9 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { AuthUser } from '@shared/models/user.model'; import { Authority } from '@shared/models/authority.enum'; -import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; @Component({ selector: 'tb-send-notification-button', @@ -29,24 +28,10 @@ export class SendNotificationButtonComponent { private authUser: AuthUser = getCurrentAuthUser(this.store); - private hasAiPermission: boolean = getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - this.userPermissionsService.hasGenericPermission(Resource.NOTIFICATION, Operation.WRITE); - constructor(private dialog: MatDialog, private store: Store, private activeComponentService: ActiveComponentService, - private userPermissionsService: UserPermissionsService, - private panelService: AiAssistantPanelService) { - } - - showAiAssistant(): boolean { - return this.hasAiPermission && !this.panelService.open(); - } - - toggleAiAssistant($event: Event): void { - $event?.stopPropagation(); - this.panelService.toggle(); + private userPermissionsService: UserPermissionsService) { } sendNotification($event: Event) { diff --git a/ui-ngx/src/app/modules/home/components/router-tabs.component.scss b/ui-ngx/src/app/modules/home/components/router-tabs.component.scss index 6bec0637c1..d2ec215b0d 100644 --- a/ui-ngx/src/app/modules/home/components/router-tabs.component.scss +++ b/ui-ngx/src/app/modules/home/components/router-tabs.component.scss @@ -13,13 +13,6 @@ } } - :host-context(.openAiAssistant) { - .tb-router-tabs-container { - margin-right: 16px; - border-right: solid 1px rgba(0, 0, 0, 0.12); - } - } - .mat-mdc-tab-nav-bar.tb-router-tabs { --mat-tab-container-height: 48px; a.mat-mdc-tab-link { diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index 852d1c4742..440dc09745 100644 --- a/ui-ngx/src/app/modules/home/home.component.html +++ b/ui-ngx/src/app/modules/home/home.component.html @@ -58,7 +58,7 @@ -
+
@if ((homeService.hideMainToolbar$ | async) === false) {
+ +
- +
} @else { -
+
{{ chat.title }} - @if (aiChats.levelOf(chat); as level) { - + (dblclick)="$event.stopPropagation(); startRename(chat)"> + @if (chat.solution) { + + }{{ chat.title }} + @if (chat.chat && aiChats.levelOf(chat.chat); as level) { + } - + } +} + + + + + @if (solution.built) { + + } + @if (solution.installed) { + + } + + + diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss index 56721bfa25..84ad826713 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -339,6 +339,20 @@ color: var(--tb-ink); } +.ai-row-ic { + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + vertical-align: -2px; + margin-right: 5px; + color: var(--tb-ink-54); +} + +.ai-row.active .ai-row-ic { + color: var(--ai-action); +} + .ai-row-menu { position: absolute; top: 50%; @@ -403,6 +417,12 @@ overflow: hidden; } +.ai-canvas.ai-solution { + width: auto; + min-width: 0; + background: var(--tb-surface, #fff); +} + .ai-canvas .ai-bar-chats { display: none; margin-left: -8px; diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts index b6d1bdf2a6..005674b81c 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -14,6 +14,8 @@ import { } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { forkJoin, of } from 'rxjs'; +import { catchError } from 'rxjs/operators'; import { DomSanitizer } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { Store } from '@ngrx/store'; @@ -24,10 +26,22 @@ import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; import { ChatInfo } from '@shared/models/ai-chat.models'; import { DAY, WEEK } from '@shared/models/time/time.models'; import { AiChatComponent } from '@home/components/ai/ai-chat.component'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { NEW_SOLUTION_ID, SolutionInfo } from '@shared/models/solution-creator.models'; +import { SolutionChatComponent } from '@home/components/ai/solution/solution-chat.component'; + +export interface AiRailRow { + id: string; + title: string; + createdTime: number; + pinned: boolean; + chat?: ChatInfo; + solution?: SolutionInfo; +} export interface AiChatsGroup { label: string; - chats: ChatInfo[]; + chats: AiRailRow[]; } @Component({ @@ -47,10 +61,13 @@ export class AiAssistantComponent implements OnInit, OnDestroy { private static readonly REFRESH_MS = 20000; @ViewChild(AiChatComponent) chat: AiChatComponent; + @ViewChild(SolutionChatComponent) solutionChat: SolutionChatComponent; @ViewChild('searchInput') searchInput: ElementRef; readonly toastTarget = 'aiAssistantPage'; + readonly newSolutionId = NEW_SOLUTION_ID; + readonly shortcutModifier = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl '; railOpen = signal(this.initialRailOpen()); @@ -61,11 +78,24 @@ export class AiAssistantComponent implements OnInit, OnDestroy { chatId = signal(undefined); + solutionId = signal(undefined); + aiChats = inject(AiChatsService); + aiSolutions = inject(AiSolutionsService); + + rows = computed(() => [ + ...this.aiChats.chats().map(chat => ({ + id: chat.id, title: chat.title, createdTime: chat.createdTime, pinned: !!chat.pinned, chat + })), + ...this.aiSolutions.solutions().map(solution => ({ + id: solution.id, title: this.aiSolutions.titleOf(solution), createdTime: solution.createdTime ?? 0, pinned: false, solution + })) + ].sort((a, b) => b.createdTime - a.createdTime)); + groups = computed(() => { const query = this.query().trim().toLowerCase(); - const chats = this.aiChats.chats(); + const chats = this.rows(); if (query) { const found = chats.filter(chat => (chat.title ?? '').toLowerCase().includes(query)); return found.length @@ -85,7 +115,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy { const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4; groups[index].chats.push(chat); } - const needsFirst = (chat: ChatInfo) => this.aiChats.needsAttention(chat) ? 0 : 1; + const needsFirst = (row: AiRailRow) => row.chat && this.aiChats.needsAttention(row.chat) ? 0 : 1; groups.forEach(group => group.chats.sort((a, b) => needsFirst(a) - needsFirst(b))); return groups.filter(group => group.chats.length); }); @@ -123,14 +153,20 @@ export class AiAssistantComponent implements OnInit, OnDestroy { private browsing = false; + private pendingEdit: string | null = null; + + private ready = signal(false); + private urlEffect = effect(() => { const chatId = this.chatId() ?? null; - if (this.route.snapshot.queryParamMap.get('chatId') !== chatId && this.aiChats.loaded()) { + const solutionId = this.solutionId() ?? null; + const params = this.route.snapshot.queryParamMap; + if ((params.get('chatId') !== chatId || params.get('solutionId') !== solutionId) && this.ready()) { const browsing = this.browsing; this.browsing = false; this.router.navigate([], { relativeTo: this.route, - queryParams: {chatId}, + queryParams: {chatId, solutionId}, queryParamsHandling: 'merge', replaceUrl: !browsing }); @@ -138,8 +174,8 @@ export class AiAssistantComponent implements OnInit, OnDestroy { }); private urlSubscription = this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(params => { - if (this.aiChats.loaded()) { - this.openFromUrl(params.get('chatId')); + if (this.ready()) { + this.openFromUrl(params.get('chatId'), params.get('solutionId')); } }); @@ -154,11 +190,22 @@ export class AiAssistantComponent implements OnInit, OnDestroy { } ngOnInit(): void { - this.aiChats.load().subscribe({ - next: chats => { - this.openFromUrl(this.route.snapshot.queryParamMap.get('chatId'), chats); + forkJoin([ + this.aiSolutions.load().pipe(catchError(err => { + this.showErrorMessage(err); + return of([]); + })), + this.aiChats.load() + ]).subscribe({ + next: ([, chats]) => { + const params = this.route.snapshot.queryParamMap; + this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats); + this.ready.set(true); }, - error: err => this.showErrorMessage(err) + error: err => { + this.ready.set(true); + this.showErrorMessage(err); + } }); } @@ -198,11 +245,74 @@ export class AiAssistantComponent implements OnInit, OnDestroy { newChat(): void { this.settleRail(); - this.browsing = !!this.chatId(); + this.browsing = !!this.chatId() || !!this.solutionId(); + this.solutionId.set(undefined); this.chatId.set(undefined); setTimeout(() => this.chat?.focus()); } + newSolution(): void { + this.settleRail(); + this.openSolution(NEW_SOLUTION_ID); + } + + selectRow(row: AiRailRow): void { + if (row.solution) { + this.settleRail(); + this.openSolution(row.solution.id); + } else if (row.chat) { + this.selectChat(row.chat); + } + } + + isActive(row: AiRailRow): boolean { + return row.solution ? row.id === this.solutionId() : row.id === this.chatId() && !this.solutionId(); + } + + editDesign(solution: SolutionInfo): void { + if (this.solutionId() === solution.id && this.solutionChat) { + this.solutionChat.editDesign(); + return; + } + this.pendingEdit = solution.id; + this.openSolution(solution.id); + } + + onSolutionLoaded(solutionId: string): void { + if (this.pendingEdit === solutionId) { + this.pendingEdit = null; + this.solutionChat?.editDesign(); + } + } + + uninstallSolution(solution: SolutionInfo): void { + this.aiSolutions.confirmAndUninstall(solution).subscribe({ + next: info => { + if (info && this.solutionId() === solution.id) { + this.solutionChat?.updatedSolution(info); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + deleteSolution(solution: SolutionInfo): void { + this.aiSolutions.confirmAndDelete(solution).subscribe({ + next: deleted => { + if (deleted && this.solutionId() === solution.id) { + this.solutionId.set(undefined); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + private openSolution(solutionId: string): void { + this.browsing = solutionId !== this.solutionId(); + this.chatId.set(undefined); + this.solutionId.set(solutionId); + } + openWaiting(): void { const waiting = this.waiting(); if (waiting.length === 1) { @@ -215,11 +325,12 @@ export class AiAssistantComponent implements OnInit, OnDestroy { selectChat(chat: ChatInfo): void { this.settleRail(); - this.browsing = chat.id !== this.chatId(); + this.browsing = chat.id !== this.chatId() || !!this.solutionId(); + this.solutionId.set(undefined); this.chatId.set(chat.id); } - startRename(chat: ChatInfo): void { + startRename(chat: {id: string}): void { this.setRailOpen(true); this.renamingId.set(chat.id); setTimeout(() => { @@ -240,14 +351,26 @@ export class AiAssistantComponent implements OnInit, OnDestroy { } } - finishRename(chat: ChatInfo, value: string): void { - if (this.renamingId() !== chat.id) { + finishRename(row: AiRailRow, value: string): void { + if (this.renamingId() !== row.id) { return; } this.renamingId.set(null); const title = value.trim(); - if (title && title !== chat.title) { - this.aiChats.rename(chat.id, title).subscribe({error: err => this.showErrorMessage(err)}); + if (!title || title === row.title) { + return; + } + if (row.solution) { + this.aiSolutions.rename(row.solution, title).subscribe({ + next: info => { + if (this.solutionId() === row.id) { + this.solutionChat?.updatedSolution(info); + } + }, + error: err => this.showErrorMessage(err) + }); + } else { + this.aiChats.rename(row.id, title).subscribe({error: err => this.showErrorMessage(err)}); } } @@ -259,8 +382,22 @@ export class AiAssistantComponent implements OnInit, OnDestroy { this.aiChats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); } - private openFromUrl(chatId: string | null, chats = this.aiChats.chats()): void { - const known = !!chatId && chats.some(chat => chat.id === chatId); + private openFromUrl(chatId: string | null, solutionId: string | null, chats = this.aiChats.chats()): void { + const knownSolution = !solutionId || solutionId === NEW_SOLUTION_ID || !this.aiSolutions.loaded() || !!this.aiSolutions.find(solutionId); + if (!knownSolution) { + this.router.navigate([], { + relativeTo: this.route, + queryParams: {chatId: null, solutionId: NEW_SOLUTION_ID}, + queryParamsHandling: 'merge', + replaceUrl: true + }); + return; + } + const nextSolution = solutionId || undefined; + if (nextSolution !== this.solutionId()) { + this.solutionId.set(nextSolution); + } + const known = !nextSolution && !!chatId && chats.some(chat => chat.id === chatId); const next = known ? chatId : undefined; if (next !== this.chatId()) { this.chatId.set(next); diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts index c59b5a2ab5..73e412e3eb 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts @@ -6,6 +6,7 @@ import { SharedModule } from '@shared/shared.module'; import { AiAssistantComponent } from '@home/pages/ai-assistant/ai-assistant.component'; import { AiModule } from '@home/components/ai/ai.module'; import { AiAssistantRoutingModule } from '@home/pages/ai-assistant/ai-assistant-routing.module'; +import { SolutionChatModule } from '@home/components/ai/solution/solution-chat.module'; @NgModule({ declarations: [ @@ -15,6 +16,7 @@ import { AiAssistantRoutingModule } from '@home/pages/ai-assistant/ai-assistant- CommonModule, SharedModule, AiModule, + SolutionChatModule, AiAssistantRoutingModule ] }) diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html deleted file mode 100644 index 0ca38ceb57..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.html +++ /dev/null @@ -1,78 +0,0 @@ - - diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss deleted file mode 100644 index cac17e2ad8..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.scss +++ /dev/null @@ -1,133 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - border-radius: 8px; - .side-bar { - border-radius: 8px; - border: 1px solid rgba(0, 0, 0, 0.12); - width: 56px; - height: 100%; - padding: 12px 8px; - display: flex; - flex-direction: column; - - &.with-transition { - transition: width 0.15s ease-in-out; - } - - &.expanded { - width: 240px; - } - &:not(.expanded) { - cursor: pointer; - } - } - .list-chats { - overflow: auto; - --mat-button-text-label-text-weight: 400; - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.87); - .title { - padding: 0 8px; - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.38); - margin-bottom: 8px; - } - a { - letter-spacing: 0.25px; - border-radius: 4px; - } - - } - .icon-button { - font-size: 0; - display: inline-flex; - } -} - -:host ::ng-deep { - .mat-mdc-button.mat-mdc-button-base { - display: inline-flex; - width: 100%; - height: 40px; - min-height: 40px; - align-items: center; - overflow: hidden; - line-height: 32px; - border-radius: 0; - .actions:not(:hover) { - --mat-button-text-hover-state-layer-opacity: 0; - } - .actions:not(.open-menu) { - display: none; - } - &:hover { - background-color: rgba(255,255,255,0.08); - padding-right: 0; - .actions { - display: block; - } - } - &.tb-active { - --mat-button-text-hover-state-layer-opacity: 0; - - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; - } - } - .mat-icon { - margin-right: 8px; - } - &.menu { - &.open-menu { - padding-right: 0; - .mat-mdc-button-persistent-ripple::before { - opacity: var(--mat-button-text-hover-state-layer-opacity, var(--mat-app-hover-state-layer-opacity)); - content: ""; - } - } - .mat-icon { - margin: auto; - } - } - span.mdc-button__label { - width: 100%; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - display: inline-flex; - align-items: center; - & > span { - flex: 1; - overflow: hidden; - text-overflow: ellipsis; - } - } - } -} -::ng-deep { - .solution-menu.mat-mdc-menu-panel { - --mat-menu-item-spacing: 8px; - --mat-menu-item-label-text-size: 14px; - --mat-menu-item-with-icon-leading-spacing: 12px; - --mat-menu-item-with-icon-trailing-spacing: 12px; - - .mat-mdc-menu-item { - min-height: 40px; - } - - .delete { - --mat-menu-item-icon-color: var(--tb-accent-500); - --mat-menu-item-label-text-color: var(--tb-accent-500); - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts deleted file mode 100644 index 6051b13301..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/side-bar/solution-side-bar.component.ts +++ /dev/null @@ -1,179 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, EventEmitter, OnInit, Output, signal } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; -import { SolutionCreatorInfo, SolutionInfo } from '@shared/models/solution-creator.models'; -import { ActivatedRoute, Router } from '@angular/router'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; -import { AppState } from '@core/core.state'; -import { select, Store } from '@ngrx/store'; -import { selectUserSettingsProperty } from '@core/auth/auth.selectors'; -import { distinctUntilChanged, skip, take } from 'rxjs/operators'; -import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; -import { ActionPreferencesPutUserSettings } from '@core/auth/auth.actions'; -import { HttpErrorResponse } from '@angular/common/http'; -import { DomSanitizer } from '@angular/platform-browser'; -import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; - -@Component({ - selector: 'tb-solution-side-bar', - templateUrl: './solution-side-bar.component.html', - styleUrls: ['./solution-side-bar.component.scss'], - standalone: false -}) -export class SolutionSideBarComponent extends PageComponent implements OnInit { - - isExpanded = signal(false); - solutions = signal>([]); - - enableTransition = false; - - @Output() - updatedSolution = new EventEmitter(); - - @Output() - installedChanged = new EventEmitter<{solutionId: string, installed: boolean}>(); - - constructor( - private solutionCreator: SolutionsCreatorService, - private dialog: DialogService, - private translate: TranslateService, - private router: Router, - private route: ActivatedRoute, - protected store: Store, - private sanitizer: DomSanitizer, - ) { - super(); - this.store.pipe(select(selectUserSettingsProperty('isSolutionSidebarExpanded'))).pipe( - take(1) - ).subscribe((settings: boolean) => { - if (settings) { - this.isExpanded.set(settings); - } - }) - - toObservable(this.isExpanded).pipe( - takeUntilDestroyed(), - skip(1), - distinctUntilChanged() - ).subscribe(value => { - this.store.dispatch(new ActionPreferencesPutUserSettings({isSolutionSidebarExpanded: value })); - }); - } - - ngOnInit() { - this.solutionCreator.getSolutions({ignoreLoading: true, ignoreErrors: true}).subscribe({ - next: solutions => this.solutions.set(solutions), - error: error => this.showError(error) - }); - } - - toggleSidebar($event: Event): void { - $event?.stopPropagation(); - this.enableTransition = true; - this.isExpanded.set(!this.isExpanded()); - } - - expandSidebar(): void { - if (!this.isExpanded()) { - this.enableTransition = true; - this.isExpanded.set(true); - } - } - - deleteSolution(solution: SolutionInfo): void { - this.dialog.confirm( - this.translate.instant('solution-creator.delete-solution-title', { - name: solution.solutionTitle || this.translate.instant('solution-creator.new-solution') - }), - this.translate.instant('solution-creator.delete-solution-text'), - this.translate.instant('action.no'), - this.translate.instant('solution-creator.delete-solution-confirm') - ).subscribe((value) => { - if (value) { - this.solutionCreator.deleteSolution(solution.id, {ignoreErrors: true}).subscribe({ - next: () => { - this.solutions.update(solutions => solutions.filter(s => s.id !== solution.id)); - if (this.route.snapshot.queryParamMap.has('solutionId') && this.route.snapshot.queryParamMap.get('solutionId') === solution.id) { - this.router.navigate(['/ai-solution-creator']).then(() => {}); - } - }, - error: error => this.showError(error) - }); - } - }) - } - - addNewSolutionTemplate(solution: SolutionInfo): void { - const findSolutionIndex = this.solutions().findIndex(s => s.id === solution.id); - if (findSolutionIndex !== -1) { - this.updateSolutionField(solution, solution); - } else { - this.solutions.update(solutions => [solution, ...solutions]); - } - } - - renameSolution(solution: SolutionInfo): void { - this.dialog.dialog.open(AiRenameDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - title: this.translate.instant('solution-creator.rename-solution-title'), - value: solution.solutionTitle || this.translate.instant('solution-creator.new-solution') - } - }).afterClosed().subscribe(newTitle => { - if (newTitle && newTitle !== solution.solutionTitle) { - this.solutionCreator.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(newTitle), {ignoreErrors: true}) - .subscribe({ - next: value => { - solution.solutionTitle = newTitle; - this.updatedSolution.next(value); - }, - error: error => this.showError(error) - }); - } - }); - } - - uninstallSolution(solution: SolutionInfo): void { - this.dialog.confirm( - this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: solution.solutionTitle}), - this.translate.instant('solution-creator.uninstall-solution-dialog-text'), - this.translate.instant('action.no'), - this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') - ).subscribe((value) => { - if (value) { - this.solutionCreator.uninstallSolution(solution.id, {ignoreErrors: true}).subscribe({ - next: () => { - this.updateSolutionField(solution, {installed: false}); - this.installedChanged.emit({solutionId: solution.id, installed: false}); - }, - error: error => this.showError(error) - }); - } - }); - } - - private showError(error: unknown): void { - const responseType = isNotEmptyStr((error as {error?: unknown})?.error) ? 'text' : undefined; - this.store.dispatch(new ActionNotificationShow({ - message: parseHttpErrorMessage(error as HttpErrorResponse, this.translate, responseType, this.sanitizer).message, - modern: true, - type: 'error', - target: 'solution-creator', - verticalPosition: 'top', - horizontalPosition: 'center' - })); - } - - updateSolutionField(solution: SolutionInfo | {id: string}, fields: Partial): void { - const defined = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined)); - this.solutions.update(solutions => - solutions.map(s => s.id === solution.id ? {...s, ...defined} : s) - ); - } -} diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts deleted file mode 100644 index 1a73f11d6b..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator-routing.module.ts +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { NgModule } from '@angular/core'; -import { RouterModule, Routes } from '@angular/router'; -import { Authority } from '@shared/models/authority.enum'; -import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; -import { MenuId } from '@core/services/menu.models'; -import { SolutionCreatorComponent } from '@home/pages/ai-solution-creator/solution-creator.component'; - -const routes: Routes = [ - { - path: 'ai-solution-creator', - component: SolutionCreatorComponent, - data: { - breadcrumb: { - menuId: MenuId.ai_solution_creator - }, - auth: [Authority.TENANT_ADMIN], - canActivate: (userPermissionsService: UserPermissionsService): boolean => { - return userPermissionsService.isAiEnabled() && userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); - }, - } - } -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule], - providers: [] -}) -export class SolutionCreatorRoutingModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts b/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts deleted file mode 100644 index 26ea5ee7a3..0000000000 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-creator.module.ts +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { CommonModule } from '@angular/common'; -import { SharedModule } from '@shared/shared.module'; -import { HomeComponentsModule } from '@home/components/home-components.module'; -import { NgModule } from '@angular/core'; -import { SolutionCreatorComponent } from '@home/pages/ai-solution-creator/solution-creator.component'; -import { SolutionCreatorRoutingModule } from '@home/pages/ai-solution-creator/solution-creator-routing.module'; -import { - SolutionCreatorOverviewEntitiesComponent -} from '@home/pages/ai-solution-creator/overview/solution-creator-overview-entities.component'; -import { AlarmInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/alarm-info-panel.component'; -import { EntityInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/entity-info-panel.component'; -import { IamInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/iam-info-panel.component'; -import { MetricInfoPanelComponent } from '@home/pages/ai-solution-creator/overview/metric-info-panel.component'; -import { - SolutionCreatorOverviewDashboardComponent -} from '@home/pages/ai-solution-creator/overview/solution-creator-overview-dashboard.component'; -import { SolutionSideBarComponent } from '@home/pages/ai-solution-creator/side-bar/solution-side-bar.component'; -import { - SolutionInfoDialogComponent -} from '@home/pages/ai-solution-creator/solution-info/solution-info-dialog.component'; -import { - IssuesPopoverComponent -} from '@home/pages/ai-solution-creator/solution-info/issues-popover.component'; -import { NgxGraphModule } from '@swimlane/ngx-graph'; -import { AiModule } from '@home/components/ai/ai.module'; - -@NgModule({ - declarations: [ - SolutionCreatorComponent, - SolutionCreatorOverviewEntitiesComponent, - AlarmInfoPanelComponent, - EntityInfoPanelComponent, - MetricInfoPanelComponent, - IamInfoPanelComponent, - SolutionCreatorOverviewDashboardComponent, - SolutionSideBarComponent, - SolutionInfoDialogComponent, - IssuesPopoverComponent - ], - imports: [ - CommonModule, - SharedModule, - HomeComponentsModule, - SolutionCreatorRoutingModule, - NgxGraphModule, - AiModule - ] -}) -export class SolutionCreatorModule { } diff --git a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts index db4a76d6bf..c9bb4d6817 100644 --- a/ui-ngx/src/app/modules/home/pages/home-pages.module.ts +++ b/ui-ngx/src/app/modules/home/pages/home-pages.module.ts @@ -29,7 +29,6 @@ import { DeviceProfileModule } from './device-profile/device-profile.module'; import { ApiUsageModule } from '@home/pages/api-usage/api-usage.module'; import { EdgeModule } from '@home/pages/edge/edge.module'; import { OtaUpdateModule } from '@home/pages/ota-update/ota-update.module'; -import { SolutionCreatorModule } from '@home/pages/ai-solution-creator/solution-creator.module'; import { VcModule } from '@home/pages/vc/vc.module'; import { TaskManagerModule } from '@home/pages/task-manager/task-manager.module'; import { AssetProfileModule } from '@home/pages/asset-profile/asset-profile.module'; @@ -95,7 +94,6 @@ import { AiAssistantModule } from '@home/pages/ai-assistant/ai-assistant.module' IFrameViewModule, SchedulerModule, OtaUpdateModule, - SolutionCreatorModule, VcModule, TaskManagerModule, AccountModule, diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 415d7c9468..f744647eb0 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -9,8 +9,11 @@ import { CalculatedFieldType } from '@shared/models/calculated-field.models'; import { AlarmSeverity } from '@shared/models/alarm.models'; import { AiAction, ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; +export const NEW_SOLUTION_ID = 'new'; + export interface SolutionInfo { id: string; + createdTime?: number; solutionTitle?: string; installed?: boolean; built?: boolean; 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 0d75046ed4..898c818cfc 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -1134,6 +1134,8 @@ "pin": "Pin to the top", "unpin": "Unpin", "double-click-to-rename": "Double-click to rename", + "new-solution": "New solution", + "edit-design": "Edit the design", "chats-menu": "Chats and this chat", "resize-panel": "Resize the AI Assistant panel", "resize-panel-hint": "Drag to resize; double-click to reset", From 948e43ba7dee6127533584cb83b65d37f8b64f37 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 6 Nov 2026 16:21:25 +0200 Subject: [PATCH 014/183] feat: the solution chat follows the design: the kit's head with the solution's mark, status, menu and full screen; the New solution hero with the AI light, the dotted grid and the examples filling the prompt; one transcript across the design steps with working lines in place of the loading modals; the step actions on the pane's foot; and a closing message handing over the main dashboard --- .../modules/home/components/ai/ai.module.ts | 3 + .../ai/solution/solution-chat.component.html | 366 +++++---- .../ai/solution/solution-chat.component.scss | 692 +++++++++++------- .../ai/solution/solution-chat.component.ts | 174 ++++- .../assets/locale/locale.constant-en_US.json | 12 + ui-ngx/src/theme/ai-theme.scss | 2 +- 6 files changed, 755 insertions(+), 494 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index 3f0c3800ee..376819b752 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -55,6 +55,9 @@ import { AiSparkComponent } from '@home/components/ai/ai-spark.component'; ], exports: [ AiAssistantButtonComponent, + AiWorkLineComponent, + AiRunSummaryComponent, + AiSparkComponent, AiPromptInputComponent, AiAssistantPanelComponent, AiChatComponent, diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html index 9286f5cfa6..3e477de084 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -4,147 +4,129 @@ SPDX-License-Identifier: BUSL-1.1 --> -
-
-
- @for (step of stepperLabels; track step; let i = $index) { - @let status = stepStatuses()[i]; -
-
- @if (status === 'ready') { - check - } @else { - {{ i + 1 }} - } -
- {{ step | translate }} -
- @if (i < stepperLabels.length - 1) { -
+
+ + + {{ title() || ('solution-creator.new-solution' | translate) }} + + @if (level(); as current) { + + + {{ ('ai-assistant.status-' + current) | translate }} + + } +
+ @if (title() || built()) { + + } + +
+
+
+ +@if (isInitialEmpty()) { +
+
+ +

{{ 'solution-creator.what-should-it-do' | translate }}

+

{{ 'solution-creator.what-it-becomes' | translate }}

+ + +
+ @for (ex of solutionExamples; track ex.key) { + } - } +
+

{{ 'solution-creator.limits' | translate }}

+
+
+} @else if (creatorStep()) { +
+
+
+ +
+
+
+ + +
- @switch (creatorStep()) { - @case ('chat') { -
-
- @if (isInitialEmpty()) { -
- - - -
-
solution-creator.main-title
-
solution-creator.sub-title
-
+ @if (showPane()) { + }
-
+} + + + + @if (built() && creatorStep() === 'result') { + + } + @if (installed()) { + + } + + diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss index 664c69c02f..e2f0999311 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -1,294 +1,450 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 :host { + position: relative; width: 100%; height: 100%; + min-width: 0; + min-height: 0; display: flex; + flex-direction: column; overflow: hidden; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} - .image-main-color { - color: var(--tb-primary-500); - } +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} - .solution-creator { - & > * { - background-color: #fff; - } +.sol-head { + position: relative; + z-index: 2; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + background: var(--tb-surface); +} - .solution-content { - border: 0; - } +.sol-head-mark { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); +} - .solution-stepper-header { - display: flex; - align-items: center; - padding: 12px 24px; - flex-shrink: 0; - border-bottom: 1px solid rgba(0, 0, 0, .12); - max-height: 56px; - opacity: 1; - overflow: hidden; - transition: max-height 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - padding 400ms cubic-bezier(0.25, 0.8, 0.25, 1), - border-bottom-width 400ms cubic-bezier(0.25, 0.8, 0.25, 1); - - &.collapsed { - max-height: 0; - opacity: 0; - padding-top: 0; - padding-bottom: 0; - border-bottom-width: 0; - } - - .stepper-step { - display: flex; - align-items: center; - gap: 8px; - - .stepper-icon { - width: 24px; - height: 24px; - border-radius: 50%; - display: flex; - align-items: center; - justify-content: center; - font-size: 12px; - font-weight: 500; - flex-shrink: 0; - background-color: rgba(0, 0, 0, .12); - color: rgba(0, 0, 0, .54); - transition: background-color 300ms ease, color 300ms ease; - } - - .stepper-label { - font-size: 14px; - color: rgba(0, 0, 0, .54); - white-space: nowrap; - transition: color 300ms ease, text-shadow 300ms ease; - } - - &.active, - &.ready { - .stepper-icon { - background-color: var(--tb-primary-500); - color: #fff; - } - - .stepper-label { - color: rgba(0, 0, 0, .87); - } - } - - &.active .stepper-label { - text-shadow: 0 0 .65px currentColor, 0 0 .65px currentColor; - } - - &.ready { - cursor: pointer; - - &:hover { - .stepper-icon { - background-color: var(--tb-primary-700); - } - - .stepper-label { - color: var(--tb-primary-700); - } - } - } - } - - .stepper-connector { - flex: 1; - height: 1px; - margin: 0 8px; - background-color: rgba(0, 0, 0, .12); - transition: background-color 300ms ease; - - &.completed { - background-color: var(--tb-primary-500); - } - } - } +.sol-head-name { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font: 500 15px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} - .chat-container { - overflow: hidden; - min-height: 0; +.sol-head-status { + flex: none; + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 12.5px/20px var(--tb-font); + color: var(--tb-ink-54); + white-space: nowrap; + + .tb-ai-status-mark { + width: 10px; + height: 10px; + + &.running::before { + width: 8px; + height: 8px; + border-width: 1.5px; } + } +} - .chat-messages-container { - position: relative; - display: flex; - flex: 1 1 auto; - min-height: 0; - width: 100%; - max-width: min(800px, 100%); - } +.sol-head-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} - .chat { - flex: 1; - padding: 8px; - position: relative; - - & > * { - z-index: 1; - } - - &::before { - background: - radial-gradient(circle, rgba(0, 0, 0, 0.08) 1px, transparent 1px) 0 0 / 16px 16px repeat, - radial-gradient(185.49% 141.73% at -0.44% 0%, #FFF 40%, var(--tb-primary-100) 100%); - content: ""; - position: absolute; - inset: 0; - transition-duration: 600ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - transition-property: opacity; - opacity: 0; - } - - &.background { - &::before { - opacity: 1; - } - } - - .welcome-content { - position: absolute; - bottom: calc(50% + 16px); - left: 50%; - transform: translateX(-50%); - display: flex; - flex-direction: column; - align-items: center; - gap: 24px; - z-index: 1; - width: calc(100% - 16px); - } - - .action { - &.action-centered { - position: absolute; - top: 50%; - left: 50%; - transform: translateX(-50%); - width: calc(100% - 16px); - max-width: 800px; - } - - tb-ai-prompt-input { - max-width: 800px; - display: block; - } - - .tb-dynamic-button { - transition-duration: 600ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - transition-property: opacity; - opacity: 1; - - @starting-style { - opacity: 0; - } - } - - & > div { - max-width: 800px; - width: 100%; - } - } - - .example-chips { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 8px; - max-width: 670px !important; - max-height: 40px; - overflow: hidden; - transition: max-height 100ms ease; - --mat-button-outlined-label-text-color: rgba(0, 0, 0, 0.76); - --mat-button-outlined-container-height: 32px; - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.16); - --mat-button-outlined-container-shape: 20px; - - &.expanded { - max-height: 200px; - } - - .example-chip { - background-color: #fff; - } - } - - .more-toggle { - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.54); - --mat-button-text-container-height: 32px; - margin-top: -8px; - } - - .long-wait { - border: 1px solid rgba(0, 0, 0, 0.12); - padding: 40px; - animation: fadeInScale 0.3s ease-in-out forwards; - opacity: 0; - transform: scale(0.95); - - &.ng-leave { - animation: fadeOutScale 0.3s ease-in-out forwards; - } - - img { - width: 100px; - } - } +.sol-head-status + .sol-head-actions { + margin-left: 0; +} - } +.sol-ib { + flex: none; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } - .overview { - flex: 0 0 0; - display: flex; - min-width: 0; - min-height: 0; - - &.entering { - animation: slide-in 400ms ease-in-out forwards; - transition-duration: 400ms; - transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); - animation-name: slide-in; - transition-property: flex-basis; - } - - @keyframes slide-in { - from { - flex-basis: 0; - } - to { - flex-basis: 60%; - } - } + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } +} + +.sol-toast { + position: absolute; + inset: 48px 0 auto; + pointer-events: none; +} + +.sol-hero { + --sol-dot: color-mix(in srgb, var(--tb-ink) 9%, transparent); + position: relative; + isolation: isolate; + flex: 1; + min-height: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 48px 24px 56px; + box-sizing: border-box; + overflow: auto; + contain: paint; + background: var(--ai-field-wash); + + &::after { + content: ''; + position: absolute; + left: -20vw; + top: -20vh; + width: 140vw; + height: 140vh; + z-index: -1; + pointer-events: none; + background: var(--ai-field-wash); + opacity: .9; + filter: blur(16px); + will-change: transform; + animation: sol-drift 16s ease-in-out infinite alternate; + } + &::before { + content: ''; + position: absolute; + inset: -8px; + z-index: 0; + pointer-events: none; + mix-blend-mode: multiply; + will-change: transform; + animation: sol-dots 26s ease-in-out infinite alternate; + background: radial-gradient(circle, var(--sol-dot) 1px, transparent 1.4px) 0 0 / 16px 16px; + mask-image: radial-gradient(ellipse 56% 52% at 50% 44%, transparent 0%, rgba(0, 0, 0, .3) 55%, #000 100%), linear-gradient(180deg, #000 50%, transparent 100%); + mask-composite: intersect; + } + + @media (prefers-reduced-motion: reduce) { + &::before, &::after { + animation: none; } } +} + +@keyframes sol-drift { + 0% { transform: translate(-3%, -2%); } + 50% { transform: translate(3%, 2%); } + 100% { transform: translate(-1%, 3%); } +} + +@keyframes sol-dots { + from { transform: translate(-5px, -3px); } + to { transform: translate(5px, 4px); } +} + +.sol-hero-in { + position: relative; + z-index: 1; + width: 100%; + max-width: 720px; + margin: auto 0; + text-align: center; +} + +.sol-mark { + --ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), + linear-gradient(135deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, + color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, + color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); + --ai-mark-edge: 0 10px 28px color-mix(in oklab, var(--tb-ink) 24%, transparent); + --ai-mark-ink: var(--ai-on-action); + --ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); + display: flex; + margin: 0 auto 14px; +} + +.sol-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: -0.2px; + color: var(--tb-ink); +} + +.sol-lead { + margin: 8px auto 0; + max-width: 540px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink-76); + text-wrap: balance; +} - .solution-result { - .title { - font-size: 28px; - font-weight: 500; - line-height: 36px; - letter-spacing: 0.1px; - margin-bottom: 8px; +.sol-hero-input { + display: block; + margin-top: 24px; + text-align: left; +} + +.sol-examples { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 6px; + max-width: 600px; + margin: 22px auto 0; + + .ob-chip { + gap: 8px; + padding: 0 16px 0 12px; + + .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--tb-ink-76); } - .sub-title { - font-size: 16px; - line-height: 24px; - letter-spacing: 0.2px; + } +} + +.sol-hero-foot { + margin: 20px 0 0; + letter-spacing: var(--chat-text-ls); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); +} + +.sol-cols { + flex: 1; + min-height: 0; + display: flex; +} + +.sol-chat { + position: relative; + flex: 1 1 0; + min-width: 0; + display: flex; + flex-direction: column; +} + +.sol-cols.with-pane .sol-chat { + min-width: 420px; +} + +.sol-log { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: 20px 20px 0; + container: k-chat / inline-size; +} + +.sol-log-in { + width: 100%; + max-width: 760px; + margin: 0 auto; + padding-bottom: 24px; +} + +.sol-chips { + margin-top: 14px; +} + +.sol-closing { + margin-top: var(--chat-turn-gap, 28px); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + + p { + margin: 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + } + + .sol-note { + margin-top: 12px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-54); + } +} + +.sol-work { + margin-top: var(--chat-turn-gap, 28px); +} + +.sol-composer { + position: relative; + flex: none; + width: 100%; + max-width: 760px; + margin: 0 auto; + padding: 0 20px 14px; + box-sizing: border-box; +} + +.sol-toast-chat { + position: absolute; + inset: auto 0 100%; + pointer-events: none; +} + +.sol-pane { + flex: 0 0 60%; + min-width: 360px; + max-width: calc(100% - 420px); + display: flex; + flex-direction: column; + min-height: 0; + border-left: 1px solid var(--tb-line); + background: var(--tb-surface); + animation: sol-pane-in 280ms cubic-bezier(.05, .7, .1, 1) both; + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes sol-pane-in { + from { + opacity: 0; + transform: translateX(24px); + } +} + +.sol-pane-body { + flex: 1; + min-height: 0; + display: flex; + overflow: auto; + + .overview { + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + } +} + +.sol-pane-foot { + flex: none; + display: flex; + align-items: center; + gap: 8px; + margin: 0; + padding: 10px 16px; + border-top: 1px solid var(--tb-line); + background: var(--tb-surface); + + .warn { + --mat-button-text-label-text-color: var(--tb-crit); + --mdc-text-button-label-text-color: var(--tb-crit); + } +} + +.sol-spacer { + flex: 1; +} + +.sol-result { + margin: auto; + padding: 32px 24px; + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + gap: 8px; + color: var(--tb-ink); +} + +.sol-result-pic { + color: var(--tb-primary-500); + margin-bottom: 8px; +} + +.sol-result-title { + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); +} + +.sol-result-sub { + max-width: 420px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + color: var(--tb-ink-76); +} + +@media (max-width: 959px) { + .sol-cols.with-pane { + flex-direction: column; + + .sol-chat { + min-width: 0; + flex: 1 1 50%; } - .divider-text { - line-height: 20px; - font-size: 14px; - font-weight: 500; + + .sol-pane { + flex: 1 1 50%; + min-width: 0; + max-width: none; + border-left: 0; + border-top: 1px solid var(--tb-line); } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts index fcd9f203a9..a70965461f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -40,9 +40,8 @@ import { } from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; -import { DynamicMatDialog } from '@shared/components/dialog/dynamic/dynamic-dialog'; -import { generatedStateImages } from '@home/components/ai/ai.models'; +import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; +import { EntityId } from '@shared/models/id/entity-id'; @Component({ selector: 'tb-solution-chat', @@ -56,6 +55,10 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe @ViewChild(AiChatMessagesComponent) chatMessages: AiChatMessagesComponent; @Output() loaded = new EventEmitter(); + get hostElement(): HTMLElement { + return this.elementRef.nativeElement; + } + isReadyStep = signal(false); skipInterviewAllowed = signal(false); solutionStep = signal(SolutionStep.INITIAL_CONFIGURATION); @@ -64,9 +67,26 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe messages = signal([]); loading = signal(false); - loadingLongTime = signal(false); isGenerating = signal(false); + work = signal<{words: string; kind: 'think' | 'gen' | 'install'; since: number} | null>(null); + + fullscreen = signal(false); + + title = signal(''); + + built = signal(false); + + installed = signal(false); + + mainDashboard = signal([]); + + level = computed<'running' | 'needs' | null>(() => this.loading() || this.isGenerating() + ? 'running' + : this.isReadyStep() && this.creatorStep() === 'chat' && !this.built() ? 'needs' : null); + + showPane = computed(() => this.creatorStep() === 'result' || (this.isReadyStep() && !this.isGenerating())); + showMoreExamples = signal(false); isInitialEmpty = computed(() => @@ -76,9 +96,9 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe !this.loading() ); - activePlaceholder = computed(() => - this.isInitialEmpty() ? 'solution-creator.describe-solution-you-want' : 'solution-creator.enter-your-prompt' - ); + activePlaceholder = computed(() => this.isInitialEmpty() + ? 'solution-creator.describe-solution-you-want' + : this.creatorStep() === 'result' ? 'solution-creator.ask-about-solution' : 'solution-creator.say-what-to-change'); activeStepIndex = computed(() => { if (!this.creatorStep()) { @@ -147,7 +167,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe { key: 'coffeeMonitor', labelKey: 'solution-creator.coffee-machine-monitoring', - icon: 'local_cafe', + icon: 'coffee', message: 'I want to monitor my coffee machine. It brews espresso, cappuccino, latte, and americano.\n\n' + 'I need to track stock levels (beans, milk, water, cups), waste fullness, and temperatures. ' + 'I also want to calculate daily totals for each drink type and daily revenue.\n\n' + @@ -156,7 +176,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe { key: 'lorawanTracker', labelKey: 'solution-creator.lorawan-tracking', - icon: 'sensors', + icon: 'cell_tower', message: 'I need a simple device management dashboard for monitoring my LoRaWAN tracker devices and connectivity.\n' + 'I want to assign a label to device and see them on the map.\n' + 'I also want to browse the device telemetry related to signal strength and raise alerts when device is offline, low battery or low signal strength.' @@ -187,7 +207,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe { key: 'weatherMonitoring', labelKey: 'solution-creator.weather-monitoring', - icon: 'wb_cloudy', + icon: 'thermostat', message: 'I want to monitor outdoor weather conditions across multiple locations using weather stations. ' + 'Each station reports standard atmospheric data — temperature, humidity, pressure, wind speed and direction, and rainfall.\n\n' + 'Show all stations on a map. Alert when conditions reach extreme levels such as frost, strong wind, or heavy rainfall.' @@ -195,7 +215,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe { key: 'fleetGeofencing', labelKey: 'solution-creator.fleet-geofencing', - icon: 'directions_car', + icon: 'local_shipping', message: 'I want to build a fleet tracking solution for transport companies. Vehicles are tracked by GPS in real time and must operate within designated allowed zones while avoiding restricted areas.\n\n' + 'Raise an alarm when a vehicle enters a restricted zone or leaves an allowed zone.' }, @@ -206,7 +226,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe dashboardsOverview: DashboardsOverview[]; solutionName: string; - loadingImage: string; private solutionId: string; private _solutionInfo: SolutionCreatorInfo; @@ -217,13 +236,18 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private set solutionInfo(value: SolutionCreatorInfo) { this._solutionInfo = value; + this.title.set(value?.data?.solutionTitle ?? ''); + this.built.set(!!value?.metadata?.built); + this.installed.set(!!value?.metadata?.installed); + const main = value?.metadata?.installResult?.mainDashboardId; + this.mainDashboard.set(value?.metadata?.installed && main ? [main] : []); this.updateStepStatuses(); } private messages$ = toObservable(this.messages); private forceScroll = false; private cancelPending$ = new Subject(); - private loadingTimer: NodeJS.Timeout; + private workTimers: NodeJS.Timeout[] = []; constructor(private route: ActivatedRoute, private solutionCreator: SolutionsCreatorService, @@ -233,7 +257,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private dialogService: DialogService, private translate: TranslateService, private sanitizer: DomSanitizer, - private dynamicMatDialog: DynamicMatDialog, private aiSolutions: AiSolutionsService) { super(); @@ -250,17 +273,17 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe const animationPanel: Element = this.elementRef.nativeElement.querySelector('.overview'); if (animationPanel) { animationPanel.addEventListener('animationend', () => { - this.chatMessages?.scrollToBottom('instant'); + this.scrollLogToEnd(); }, { once: true }); } else { - this.chatMessages?.scrollToBottom('instant'); + this.scrollLogToEnd(); } }, 0); this.forceScroll = false; } else if (lastMsg?.from === 'USER') { - setTimeout(() => this.chatMessages?.scrollToBottom('smooth'), 0); + setTimeout(() => this.scrollLogToEnd(true), 0); } else if (lastMsg?.from === 'AI') { - setTimeout(() => this.chatMessages?.scrollToLastUserMessage(), 0); + setTimeout(() => this.scrollLastQuestionToTop(), 0); } }) } @@ -299,14 +322,63 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.forceScroll = true; this.initPredefinedSolution(); this.loaded.emit(solution.id); + setTimeout(() => this.scrollLogToEnd(), 300); }); } ngOnDestroy(): void { + this.clearWork(); this.cancelPending$.next(); this.cancelPending$.complete(); } + toggleFullscreen(): void { + this.fullscreen.update(value => !value); + } + + renameSolution(): void { + if (!this.solutionId) { + return; + } + this.dialogService.dialog.open(AiRenameDialogComponent, { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + title: this.translate.instant('solution-creator.rename-solution-title'), + value: this.title() || this.translate.instant('solution-creator.new-solution') + } + }).afterClosed().subscribe(newTitle => { + const title = newTitle?.trim(); + if (title && title !== this.title()) { + this.aiSolutions.rename(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId}, title).subscribe({ + next: value => this.updatedSolution(value), + error: err => this.showErrorMessage(err) + }); + } + }); + } + + deleteSolution(): void { + if (!this.solutionId) { + return; + } + this.aiSolutions.confirmAndDelete(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId, solutionTitle: this.title()}).subscribe({ + next: deleted => { + if (deleted) { + this.router.navigate([], {relativeTo: this.route, queryParams: {solutionId: NEW_SOLUTION_ID}, queryParamsHandling: 'merge'}); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + fillExample(key: string): void { + const example = this.solutionExamples.find(ex => ex.key === key); + if (example) { + this.promptInput?.setValue(example.message); + } + } + nextStep() { if(this.solutionInfo.states[this.solutionStep()]?.status === SolutionStepStatus.READY) { if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { @@ -396,6 +468,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } Object.assign(this.solutionInfo.metadata.installResult, value); this.solutionInfo.metadata.installed = true; + this.solutionInfo = this.solutionInfo; this.aiSolutions.update(this.solutionId, {installed: true}); progressSubject.next(); progressSubject.complete(); @@ -588,6 +661,21 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe ); } + private scrollLogToEnd(smooth = false): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + log?.scrollTo({top: log.scrollHeight, behavior: smooth ? 'smooth' : 'auto'}); + } + + private scrollLastQuestionToTop(): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + const questions = log?.querySelectorAll('tb-ai-chat-messages .user'); + const last = questions?.length ? questions[questions.length - 1] : null; + if (log && last) { + const top = log.scrollTop + last.getBoundingClientRect().top - log.getBoundingClientRect().top - 12; + log.scrollTo({top, behavior: 'smooth'}); + } + } + private rememberSolution(): void { if (this.solutionInfo) { this.aiSolutions.upsert(this.solutionInfo); @@ -605,7 +693,11 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } private updatedCurrentMsg() { - this.messages.set(this.solutionInfo.states[this.solutionStep()]?.messages?.filter(msg => msg.from === 'AI' || msg.from === 'USER') ?? []); + const steps = this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION + ? [SolutionStep.INITIAL_CONFIGURATION, SolutionStep.DASHBOARDS_CONFIGURATION] + : [SolutionStep.INITIAL_CONFIGURATION]; + this.messages.set(steps.flatMap(step => this.solutionInfo.states[step]?.messages ?? []) + .filter(msg => msg.from === 'AI' || (msg.from === 'USER' && !/^<[a-z-]+\/>$/.test((msg.content ?? '').trim())))); const stepState = this.solutionInfo.states[this.solutionStep()]; if (stepState?.status === SolutionStepStatus.READY) { this.solutionName = this.solutionInfo.data?.solutionTitle; @@ -639,6 +731,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } private resetSolution(): void { + this.clearWork(); this.cancelPending$.next(); this.isReadyStep.set(false); this.skipInterviewAllowed.set(false); @@ -656,6 +749,10 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private initPredefinedSolution(): void { if (this.solutionInfo.metadata?.built) { + if (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]) { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + } + this.updatedCurrentMsg(); this.creatorStep.set('result'); return; } @@ -716,16 +813,25 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } } - return this.dynamicMatDialog.open(AiLoadingModalComponent, { - containerElement: this.elementRef.nativeElement, - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - backdropClass: 'ai-backdrop-filter', - data: { - messages, - estimateWaitTime, - } + const creating = messages[0]?.text === 'solution-creator.step-loading-creating-entities'; + return this.startWork(messages, creating ? 'install' : 'gen', estimateWaitTime); + } + + private startWork(messages: Array<{text: string; delay: number}>, kind: 'think' | 'gen' | 'install', _estimate?: number): {close: () => void} { + this.clearWork(); + const since = Date.now(); + let at = 0; + messages.forEach(message => { + at += message.delay; + this.workTimers.push(setTimeout(() => this.work.set({words: this.translate.instant(message.text), kind, since}), at)); }); + return {close: () => this.clearWork()}; + } + + private clearWork(): void { + this.workTimers.forEach(timer => clearTimeout(timer)); + this.workTimers = []; + this.work.set(null); } toggleMoreExamples(): void { @@ -745,15 +851,15 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private initLoadingState(): void { this.loading.set(true); - this.loadingImage = generatedStateImages[Math.floor(Math.random() * generatedStateImages.length)]; - this.loadingTimer = setTimeout(() => { - this.loadingLongTime.set(true); - }, 5000); + if (!this.workTimers.length) { + this.startWork([{text: this.messages().length ? 'solution-creator.work-thinking' : 'solution-creator.work-reading', delay: 0}], 'think'); + } } private stopLoadingState(): void { this.loading.set(false); - this.loadingLongTime.set(false); - clearTimeout(this.loadingTimer); + if (!this.isGenerating()) { + this.clearWork(); + } } } 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 898c818cfc..803c22ed06 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -11733,6 +11733,18 @@ "select-recaptcha-enterprise-service-account-file": "Drag and drop your account credentials file" }, "solution-creator": { + "what-should-it-do": "What should the solution do?", + "what-it-becomes": "A description becomes profiles, roles, calculated fields, alarm rules and dashboards, on simulated devices.", + "example-tip": "Puts the example in the composer", + "limits": "Nothing is created in your tenant until you approve the design and install it.", + "say-what-to-change": "Say what to change in the design…", + "ask-about-solution": "Ask about the solution…", + "next-dashboards": "Next: dashboards", + "closing-installed": "The solution is installed in your tenant.", + "closing-created": "The solution is created. Install it to make its entities in your tenant.", + "closing-simulated": "Simulated data runs for seven days. A real device takes over a simulated one when it connects.", + "work-reading": "Reading your description", + "work-thinking": "Working on the design", "ai-solution-creator": "AI solution creator", "describe-solution-you-want": "Describe a solution you want to make", "enter-your-prompt": "Enter your prompt", diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index eb9e64501a..0c300e90c8 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -1253,7 +1253,7 @@ margin-top: 14px; } -.k-actions, .tb-rec-side { +.k-actions, .tb-rec-side, .sol-pane-foot { .mdc-button { height: 36px; gap: 8px; From 69bd289f12ac05c6f0df3aa341350538f222744b Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 6 Nov 2026 16:30:03 +0200 Subject: [PATCH 015/183] fix: no stray scrollbars on the AI Assistant page and the New solution hero, and the solution canvas keeps the chat's bottom gap and rounded corners --- .../ai/solution/solution-chat.component.html | 2 ++ .../ai/solution/solution-chat.component.scss | 19 ++++++++++++++----- .../src/app/modules/home/home.component.scss | 1 + .../ai-assistant/ai-assistant.component.scss | 1 + 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html index 3e477de084..adf884ace7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -34,6 +34,7 @@ @if (isInitialEmpty()) {
+

{{ 'solution-creator.what-should-it-do' | translate }}

@@ -53,6 +54,7 @@

{{ 'solution-creator.limits' | translate }}

+
} @else if (creatorStep()) {
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss index e2f0999311..17bf2c7e9f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -134,11 +134,7 @@ flex: 1; min-height: 0; display: flex; - align-items: center; - justify-content: center; - padding: 48px 24px 56px; - box-sizing: border-box; - overflow: auto; + overflow: hidden; contain: paint; background: var(--ai-field-wash); @@ -190,6 +186,19 @@ to { transform: translate(5px, 4px); } } +.sol-hero-scroll { + position: relative; + z-index: 1; + flex: 1; + min-width: 0; + display: flex; + justify-content: center; + padding: 48px 24px 56px; + box-sizing: border-box; + overflow-y: auto; + overflow-x: hidden; +} + .sol-hero-in { position: relative; z-index: 1; diff --git a/ui-ngx/src/app/modules/home/home.component.scss b/ui-ngx/src/app/modules/home/home.component.scss index b36599fb0b..9be747f736 100644 --- a/ui-ngx/src/app/modules/home/home.component.scss +++ b/ui-ngx/src/app/modules/home/home.component.scss @@ -179,6 +179,7 @@ .tb-site-content { position: relative; + overflow-x: hidden; } .tb-site-main.openAiAssistant { diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss index 84ad826713..249c2fb734 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -419,6 +419,7 @@ .ai-canvas.ai-solution { width: auto; + height: auto; min-width: 0; background: var(--tb-surface, #fff); } From a2157dd7a2c31e8d3b10909dd71f9163f6a205a6 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 6 Nov 2026 16:42:40 +0200 Subject: [PATCH 016/183] feat: the solution's design pane follows the design: Overview, Dashboards and Solution views switched in the pane's head, the overview's sections as tables with rows that open in place and a schema on the AI light's bands, each dashboard as a section, what was installed with its status per row, JSON with Apply, a loading view while a step is made, a draggable edge, and a pill on the composer that brings the closed pane back --- .../overview/alarm-info-panel.component.html | 47 -- .../overview/alarm-info-panel.component.ts | 33 -- .../overview/entity-info-panel.component.html | 114 ----- .../overview/entity-info-panel.component.scss | 85 ---- .../overview/entity-info-panel.component.ts | 49 -- .../overview/iam-info-panel.component.html | 34 -- .../overview/iam-info-panel.component.ts | 35 -- .../overview/metric-info-panel.component.html | 41 -- .../overview/metric-info-panel.component.ts | 35 -- ...-creator-overview-dashboard.component.html | 52 --- ...on-creator-overview-dashboard.component.ts | 75 --- ...n-creator-overview-entities.component.html | 315 ------------- ...n-creator-overview-entities.component.scss | 120 ----- ...ion-creator-overview-entities.component.ts | 427 ------------------ .../overview/solution-creator-overview.scss | 74 --- .../pane/solution-dashboards.component.html | 34 ++ .../pane/solution-dashboards.component.scss | 46 ++ .../pane/solution-dashboards.component.ts | 72 +++ .../pane/solution-installed.component.html | 82 ++++ .../pane/solution-installed.component.scss | 157 +++++++ .../pane/solution-installed.component.ts | 164 +++++++ .../pane/solution-overview.component.html | 268 +++++++++++ .../pane/solution-overview.component.scss | 104 +++++ .../pane/solution-overview.component.ts | 221 +++++++++ .../ai/solution/pane/solution-pane.scss | 407 +++++++++++++++++ .../ai/solution/pane/solution-schema.ts | 165 +++++++ .../ai/solution/solution-chat.component.html | 109 +++-- .../ai/solution/solution-chat.component.scss | 411 ++++++++++++++++- .../ai/solution/solution-chat.component.ts | 198 +++++++- .../ai/solution/solution-chat.module.ts | 22 +- .../shared/models/solution-creator.models.ts | 1 + .../assets/locale/locale.constant-en_US.json | 65 +++ 32 files changed, 2466 insertions(+), 1596 deletions(-) delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.html deleted file mode 100644 index 1d00ac1923..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.html +++ /dev/null @@ -1,47 +0,0 @@ - -
-
solution-creator.alarm-info
-
-
- {{ 'alarm.type' | translate }} - {{ alarm.alarmName }} -
- -
- {{ 'alarm-rule.severities' | translate }} - - @for (key of alarm.severities; track key; let last=$last) { - - {{ key }} - - @if(!last) { - , - } - } - -
- -
- {{ 'solution-creator.entity-profiles' | translate }} - {{ alarm.profileNames.join(', ') }} -
- -
- {{ 'solution-creator.condition' | translate }} - {{ alarm.condition }} -
-
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.ts deleted file mode 100644 index e1e4c2f12a..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/alarm-info-panel.component.ts +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { SolutionDescriptorAlarm } from '@shared/models/solution-creator.models'; -import { alarmSeverityColors } from '@shared/models/alarm.models'; - -@Component({ - selector: 'tb-alarm-info-panel', - templateUrl: './alarm-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class AlarmInfoPanelComponent { - - @Input() - alarm: SolutionDescriptorAlarm; - - protected readonly Object = Object; - - constructor(private popover: TbPopoverComponent) { - } - - cancel() { - this.popover.hide(); - } - - getAlarmSeverityColor(severity: string): string { - const preparedSeverity: any = severity.toUpperCase(); - return alarmSeverityColors.has(preparedSeverity) ? alarmSeverityColors.get(preparedSeverity) : null; - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.html deleted file mode 100644 index 9f6832b319..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.html +++ /dev/null @@ -1,114 +0,0 @@ - -
-
solution-creator.entity-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ entity.name }} -
- -
- {{ 'entity.entity-type' | translate }} - {{ entity.entityType }} -
- - @if (entity.scope) { -
- {{ 'solution-creator.scope' | translate }} - {{ entity.scope }} -
- - } - @if (entity.description) { -
- {{ 'solution-creator.description' | translate }} - {{ entity.description }} -
- - } - @if (entityInfoType) { - - @if (attributes?.length) { - {{ 'attribute.attributes' | translate }} - } - @if (timeseries?.length) { - {{ 'attribute.scope-telemetry' | translate }} - } - @if (relations?.length) { - {{ 'relation.relations' | translate }} - } - - @switch (entityInfoType) { - @case ('ATTRIBUTE') { - @for (key of attributes ; track key.key; let last=$last) { -
- {{ key.key }} - {{ key.dataType | titlecase }} - @if (key.enumValues) { - ({{ key.enumValues.join('/') }}) - } - -
- @if (!last) { - - } - } - } - @case ('TIMESERIES') { - @for (key of timeseries; track key.key; let last=$last) { -
- {{ key.key}} - @if (key.calculatedFieldName) { - - mdi:function-variant - - } @else if (key.units) { -  ({{ key.units }}) - } - - {{ key.dataType | titlecase }} - @if (key.enumValues) { - ({{ key.enumValues.join('/') }}) - } - -
- @if (!last) { - - } - } - } - @case ('RELATION') { - @for (relation of relations; track relation.child; let last = $last) { -
- {{ relation.child }} - {{ relation.type }} - @if (relation.cardinality) { - ({{ relation.cardinality }}) - } - -
- @if (!last) { - - } - } - } - } - } -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.scss deleted file mode 100644 index fec548ccf3..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.scss +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@import '../scss/constants'; - -.tb-entity-info-panel { - width: 400px; - display: flex; - flex-direction: column; - gap: 16px; - height: 100%; - max-height: calc(100vh - 24px); - @media #{$mat-xs} { - width: 80vw; - } - .tb-entity-info-title { - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.87); - } - .tb-entity-info-panel-content { - display: flex; - flex-direction: column; - overflow: auto; - margin: -8px; - padding: 8px; - --mat-divider-color: rgba(0, 0, 0, 0.1); - - .property { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.25px; - margin: 12px 0; - display: flex; - justify-content: space-between; - gap: 16px; - - span:first-child { - font-weight: 500; - white-space: nowrap; - min-width: 120px; - tb-icon { - vertical-align: text-bottom; - color: rgba(0, 0, 0, 0.54); - } - span { - font-weight: 400; - color: rgba(0, 0, 0, 0.54); - } - } - - span:last-child { - span { - font-style: italic; - color: rgba(0, 0, 0, 0.54); - } - } - - &.column { - flex-direction: column; - gap: 8px; - - .condition-text { - padding: 8px 12px; - background: rgba(0, 0, 0, 0.04); - border-radius: 6px; - font-size: 13px; - line-height: 18px; - color: rgba(0, 0, 0, 0.76); - white-space: pre-wrap; - word-break: break-word; - } - - .description-text { - font-size: 13px; - line-height: 18px; - color: rgba(0, 0, 0, 0.54); - white-space: pre-wrap; - word-break: break-word; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.ts deleted file mode 100644 index 8e27cd86f3..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/entity-info-panel.component.ts +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { - SolutionDescriptorEntityBaseRelation, - SolutionDescriptorEntityBaseTelemetry, - SolutionEntity -} from '@shared/models/solution-creator.models'; - -@Component({ - selector: 'tb-entity-info-panel', - templateUrl: './entity-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class EntityInfoPanelComponent implements OnInit { - - @Input() - entity: SolutionEntity; - - @Input() - relations: SolutionDescriptorEntityBaseRelation[] = []; - - entityInfoType: 'ATTRIBUTE' | 'TIMESERIES' | 'RELATION'; - - attributes: SolutionDescriptorEntityBaseTelemetry[]; - timeseries: SolutionDescriptorEntityBaseTelemetry[]; - - constructor(private popover: TbPopoverComponent) { - } - - ngOnInit() { - this.attributes = this.entity.telemetry?.filter((item) => item.telemetryType === 'ATTRIBUTE'); - this.timeseries = this.entity.telemetry?.filter((item) => item.telemetryType === 'TIMESERIES'); - if (this.attributes?.length) { - this.entityInfoType = 'ATTRIBUTE'; - } else if (this.timeseries?.length) { - this.entityInfoType = 'TIMESERIES'; - } else if (this.relations?.length) { - this.entityInfoType = 'RELATION'; - } - } - - cancel() { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.html deleted file mode 100644 index bebe45896c..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.html +++ /dev/null @@ -1,34 +0,0 @@ - -
-
solution-creator.iam-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ iam.name }} -
- -
- {{ 'permission.operation.operations' | translate }} - {{ operations }} -
- -
- {{ 'solution-creator.description' | translate }} - {{ iam.description }} -
- -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.ts deleted file mode 100644 index 486615bdf9..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/iam-info-panel.component.ts +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { SolutionDescriptorIam } from '@shared/models/solution-creator.models'; -import { TranslateService } from '@ngx-translate/core'; - -@Component({ - selector: 'tb-iam-info-panel', - templateUrl: './iam-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class IamInfoPanelComponent implements OnInit { - - @Input() - iam: SolutionDescriptorIam; - - operations: string; - - constructor(private popover: TbPopoverComponent, - private translate: TranslateService) { - } - - ngOnInit() { - this.operations = this.iam.permissions.split('') - .map(operation => this.translate.instant(`solution-creator.operation.${operation}`)) - .join(', '); - } - - cancel() { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.html deleted file mode 100644 index 4981cadea4..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.html +++ /dev/null @@ -1,41 +0,0 @@ - -
-
solution-creator.calculated-field-info
-
-
- {{ 'solution-creator.name' | translate }} - {{ metric.calculatedFieldName }} -
- -
- {{ 'solution-creator.entity-profile' | translate }} - {{ metric.profileName }} -
- -
- {{ 'solution-creator.field-type' | translate }} - {{ getMetricTypeName(metric.metricType) }} -
- - @if (metric.calculation) { -
- {{ 'solution-creator.description' | translate }} - {{ metric.calculation }} -
- - } -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.ts deleted file mode 100644 index 4312bdb8cd..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/metric-info-panel.component.ts +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Input, ViewEncapsulation } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; -import { AiMetricType, SolutionDescriptorMetric } from '@shared/models/solution-creator.models'; -import { CalculatedFieldTypeTranslations } from '@shared/models/calculated-field.models'; -import { TranslateService } from '@ngx-translate/core'; - -@Component({ - selector: 'tb-metric-info-panel', - templateUrl: './metric-info-panel.component.html', - styleUrls: ['./entity-info-panel.component.scss'], - encapsulation: ViewEncapsulation.None, - standalone: false -}) -export class MetricInfoPanelComponent { - - @Input() - metric: SolutionDescriptorMetric; - - constructor(private popover: TbPopoverComponent, - private translate: TranslateService) { - } - - cancel() { - this.popover.hide(); - } - - getMetricTypeName(value: keyof AiMetricType): string { - if (AiMetricType[value]) { - return this.translate.instant(CalculatedFieldTypeTranslations.get(AiMetricType[value]).name); - } - return value as any; - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.html deleted file mode 100644 index 690c992ffc..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.html +++ /dev/null @@ -1,52 +0,0 @@ - -
- -
{{ 'solution-creator.dashboards-overview' | translate: {name: solutionName} }}
- - {{ 'solution-creator.basic-mode' | translate }} - {{ 'solution-creator.advanced-mode' | translate }} - -
-
- @if (solutionMode.value === 'basic') { -
-
- - @for (dashboard of dashboards; track dashboard.name) { - - {{ dashboard.name }} - {{ dashboard.assignedTo }} - - } - -
-
- -
-
- } - @else { - -
- -
- } -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.ts deleted file mode 100644 index 61ecceb8e1..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-dashboard.component.ts +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { AfterContentInit, Component, EventEmitter, HostBinding, Input, OnChanges, Output } from "@angular/core"; -import { DashboardsOverview } from '@shared/models/solution-creator.models'; -import { FormBuilder } from '@angular/forms'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { deepClone } from '@core/utils'; - -@Component({ - selector: 'tb-solution-creator-overview-dashboard', - templateUrl: './solution-creator-overview-dashboard.component.html', - styleUrls: ['./solution-creator-overview.scss'], - standalone: false -}) -export class SolutionCreatorOverviewDashboardComponent implements OnChanges, AfterContentInit { - - @Input({required: true}) - dashboards: DashboardsOverview[]; - - @Input({required: true}) - solutionName: string; - - @Output() - updatedDashboards: EventEmitter = new EventEmitter(); - - @HostBinding('class.entering') - initComponent = false; - - dashboard = this.fb.control([''], {nonNullable: true}); - dashboardDescriptor = this.fb.control(null); - solutionMode = this.fb.control('basic'); - description: string; - - constructor(private fb: FormBuilder, - ) { - this.dashboard.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - const dashboard = this.dashboards.find(item => item.name === value[0]); - this.description = dashboard?.description ?? 'Not found'; - }) - - this.solutionMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'advanced') { - this.dashboardDescriptor.setValue(deepClone(this.dashboards)); - this.dashboardDescriptor.markAsPristine(); - } - }) - } - - ngOnChanges(): void { - if (this.dashboards.length) { - if (!this.dashboards.find(item => item.name === this.dashboard.value[0])) { - this.dashboard.setValue([this.dashboards[0]?.name]); - } - if (this.dashboardDescriptor.pristine) { - this.dashboardDescriptor.setValue(deepClone(this.dashboards)); - } - } - } - - ngAfterContentInit() { - requestAnimationFrame(() => { - this.initComponent = true; - }) - } - - updatedDashboardsDescriptor($event: MouseEvent) { - $event?.stopPropagation(); - this.dashboardDescriptor.markAsPristine(); - this.updatedDashboards.emit(this.dashboardDescriptor.value); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.html deleted file mode 100644 index 49ad679de6..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.html +++ /dev/null @@ -1,315 +0,0 @@ - -
- -
{{ 'solution-creator.solution-overview' | translate: {name: solutionName} }}
- - {{ 'solution-creator.basic-mode' | translate }} - {{ 'solution-creator.advanced-mode' | translate }} - -
-
- @if (solutionMode.value === 'basic') { -
-
- - @for (entity of solutionEntities; track entity) { - @if (entity.value === 'entityProfiles' || description[entity.value]?.length) { - {{ entity.title | translate }} - } - } - -
-
-
-
{{ solutionEntityTitle | translate }}
- - {{ 'solution-creator.table-view' | translate }} - {{ 'solution-creator.schema-view' | translate }} - -
- @if (profileMode.value === 'table' || solutionEntity.value[0] !== 'entityProfiles') { -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{{ 'solution-creator.name' | translate }} {{element.name}} {{ 'solution-creator.name' | translate }} {{element.calculatedFieldName}} {{ 'entity.entity-type' | translate }} {{element.entityType}} {{ 'solution-creator.data' | translate }} - @if (element.telemetry?.length || getEntityRelations(element.name).length) { -
- @for (keyInfo of element.telemetry; track keyInfo.key) { - - } - @for (relation of getEntityRelations(element.name); track relation.child) { - - } -
- } -
{{ 'solution-creator.entity-profile' | translate }} - - {{ 'alarm.type' | translate }}{{ element.alarmName }}{{ 'solution-creator.entity-profiles' | translate}} -
- @if (element.entityProfiles?.length) { -
- @for (entityProfile of element.entityProfiles; track entityProfile) { - - } -
- } -
-
{{ 'solution-creator.entity-profiles' | translate}} -
- @if (element.profileNames?.length) { -
- @for (entityProfile of element.profileNames; track entityProfile) { - - } -
- } -
-
{{ 'alarm-rule.severities' | translate }} - @for (key of element.severities; track key; let last=$last) { - - {{ key }} - - @if(!last) { - , - } - } - {{ 'permission.operation.operations' | translate }} -
- @for (operation of element.permissions.split(''); track operation) { - - } -
-
- - - - - - - - - -
-
- } @else { -
- - - - - - - - - - - - {{ cluster.label }} - - - - - - -
-
-
{{ node.label }}
-
{{ node.data?.entityType }}
-
-
- info_outline -
-
-
-
- - - - - - -
{{ link.label }}
-
-
-
-
-
-
- } -
-
- } - @else { - -
- -
- } -
-
- -
- {{ title }} -
-
- -
- @switch (type) { - @case ('TIMESERIES') { - timeline - } - @case ('ATTRIBUTE') { - mdi:alpha-a-circle-outline - } - @case ('relation') { - mdi:repeat - } - } - {{ title }} -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.scss deleted file mode 100644 index b622dacb73..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.scss +++ /dev/null @@ -1,120 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - .tb-solution-settings { - .tb-solution-settings-table-toolbar { - height: 48px; - padding: 0 12px; - display: flex; - align-items: center; - font-size: 16px; - line-height: 24px; - font-weight: 500; - } - - .tb-solution-settings-container { - &::ng-deep { - .mat-mdc-table { - .mat-mdc-header-row { - height: 48px; - - th { - font-size: 14px; - } - } - .mat-mdc-row { - height: 48px; - } - } - - .tb-primary-fill:before { - opacity: 0.1; - } - } - } - - .graph-container { - .node { - padding: 8px 12px; - border-radius: 8px; - border: 1px solid; - background: #fff; - min-width: 180px; - text-align: left; - min-height: 54px; - &.customer { - border-color: #2B90D9; - border-left-width: 4px; - } - - &.asset { - border-color: #8C46C8; - border-left-width: 4px; - } - - &.device { - border-color: #EC8B29; - border-left-width: 4px; - } - - &.user { - border-color: #40985C; - border-left-width: 4px; - } - .title { - font-weight: 500; - font-size: 14px; - line-height: 18px; - } - - .subtitle { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.76); - } - - .node-info-btn { - display: flex; - align-items: flex-start; - cursor: pointer; - color: #B1B1B1; - - &:hover { - color: rgba(0, 0, 0, 0.54); - } - } - } - .edge-label-text { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.76); - text-align: center; - background: #fff; - border: 1px solid rgba(0,0,0,0.08); - padding: 2px 6px; - border-radius: 4px; - white-space: nowrap; - max-width: fit-content; - margin: 0 auto; - } - - .cluster { - border: 2px dashed rgba(0,0,0,0.15); - border-radius: 14px; - background: rgba(0,0,0,0.02); - padding: 8px; - - .cluster-title { - font-size: 14px; - fill: rgba(0, 0, 0, 0.54); - } - } - } - } - - ::ng-deep { - .tb-chip, .tb-overflow-chip { - padding: 4px 8px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.ts deleted file mode 100644 index 404ccd4715..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview-entities.component.ts +++ /dev/null @@ -1,427 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { - AfterContentInit, - Component, - ElementRef, - EventEmitter, - HostBinding, - Input, - OnChanges, - OnDestroy, - Output, - Renderer2, - Type, - ViewChild, - ViewContainerRef -} from "@angular/core"; -import { - SolutionDescriptor, - SolutionDescriptorAlarm, - SolutionDescriptorEntityBase, - SolutionDescriptorEntityBaseRelation, - SolutionDescriptorIam, - SolutionDescriptorMetric, - SolutionEntity -} from '@shared/models/solution-creator.models'; -import { FormBuilder } from '@angular/forms'; -import { TbTableDatasource } from '@shared/components/table/table-datasource.abstract'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { deepClone } from '@core/utils'; -import { alarmSeverityColors } from '@shared/models/alarm.models'; -import { TbPopoverService } from '@shared/components/popover.service'; -import { MatIconButton } from '@angular/material/button'; -import { AlarmInfoPanelComponent } from './alarm-info-panel.component'; -import { EntityInfoPanelComponent } from './entity-info-panel.component'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { ClusterNode, Edge, GraphComponent, Node } from '@swimlane/ngx-graph'; -import { MetricInfoPanelComponent } from '@home/components/ai/solution/overview/metric-info-panel.component'; -import { IamInfoPanelComponent } from '@home/components/ai/solution/overview/iam-info-panel.component'; -import { StrictPopoverPlacements } from '@shared/components/popover.models'; - -@Component({ - selector: 'tb-solution-creator-overview-entities', - templateUrl: './solution-creator-overview-entities.component.html', - styleUrls: ['./solution-creator-overview.scss', './solution-creator-overview-entities.component.scss'], - standalone: false -}) -export class SolutionCreatorOverviewEntitiesComponent implements OnChanges, AfterContentInit, OnDestroy { - - @Input({required: true}) - description: SolutionDescriptor; - - @Input({required: true}) - solutionName: string; - - @Output() - updatedDescription: EventEmitter = new EventEmitter(); - - @HostBinding('class.entering') - initComponent = false; - - readonly solutionEntities = [ - {value: 'entityProfiles', title: 'solution-creator.entity-profiles'}, - {value: 'iam', title: 'solution-creator.iam', fullTitle: 'solution-creator.iam-full'}, - {value: 'metrics', title: 'entity.type-calculated-fields'}, - {value: 'alarms', title: 'alarm.alarms'}, - ]; - - protected readonly Object = Object; - - solutionEntity = this.fb.control(['entityProfiles'], {nonNullable: true}); - solutionEntityTitle = 'solution-creator.entity-profiles'; - solutionDescriptor = this.fb.control(null); - solutionMode = this.fb.control('basic'); - profileMode = this.fb.control('table'); - nodes: Node[] = []; - links: Edge[] = []; - clusters: ClusterNode[] = []; - @ViewChild('graphContainer', {static: false}) graphContainer: ElementRef; - @ViewChild(GraphComponent) graphComponent: GraphComponent; - private graphResizeObserver: ResizeObserver; - - displayedColumns: string[] = ['name', 'entityType', 'data', 'entityActions']; - dataSource = new EntityOverviewDatasource(); - - constructor(private fb: FormBuilder, - private popoverService: TbPopoverService, - private renderer: Renderer2, - private viewContainerRef: ViewContainerRef, - private dialog: DialogService, - private translate: TranslateService, - ) { - this.solutionEntity.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (this.profileMode.value !== 'table') { - this.profileMode.setValue('table'); - } else { - this.prepareEntityToDatasource(value[0]); - } - }) - - this.solutionMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'basic') { - this.dataSource = new EntityOverviewDatasource(); - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - } else { - this.solutionDescriptor.setValue(deepClone(this.description)); - this.solutionDescriptor.markAsPristine(); - } - }) - - this.profileMode.valueChanges.pipe( - takeUntilDestroyed() - ).subscribe(value => { - if (value === 'table') { - this.dataSource = new EntityOverviewDatasource(); - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - } else { - this.prepareSchemaData(); - requestAnimationFrame(() => this.observeGraphResize()); - } - }) - } - - ngOnChanges(): void { - if (this.description) { - if (this.description && this.solutionEntity.value[0] !== 'entityProfiles' - && !this.description[this.solutionEntity.value[0]].length) { - this.solutionEntity.setValue(['entityProfiles'], {emitEvent: false}); - } - this.prepareEntityToDatasource(this.solutionEntity.value[0]); - if (this.solutionDescriptor.pristine) { - this.solutionDescriptor.setValue(deepClone(this.description)); - } - if (this.profileMode.value !== 'table') { - this.prepareSchemaData(); - } - } - } - - ngAfterContentInit() { - requestAnimationFrame(() => { - this.initComponent = true; - }) - } - - ngOnDestroy(): void { - this.graphResizeObserver?.disconnect(); - } - - observeGraphResize(): void { - this.graphResizeObserver?.disconnect(); - if (this.graphContainer?.nativeElement) { - this.graphResizeObserver = new ResizeObserver(() => { - this.graphComponent?.basicUpdate(); - }); - this.graphResizeObserver.observe(this.graphContainer.nativeElement); - } - } - - getAlarmSeverityColor(severity: string): string { - const preparedSeverity: any = severity.toUpperCase(); - return alarmSeverityColors.has(preparedSeverity) ? alarmSeverityColors.get(preparedSeverity) : null; - } - - getEntityRelations(entityName: string): SolutionDescriptorEntityBaseRelation[] { - return this.description?.relations?.filter(r => r.parent === entityName) ?? []; - } - - openAlarmInfo(event: Event, matButton: MatIconButton, alarm: SolutionDescriptorAlarm): void { - this.openInfoPopover(event, matButton, AlarmInfoPanelComponent, true, { alarm }); - } - - openEntityInfo(event: Event, ref: MatIconButton | HTMLElement, entity: SolutionEntity, fixedPosition = true): void { - const relations = this.getEntityRelations(entity.name); - this.openInfoPopover(event, ref, EntityInfoPanelComponent, fixedPosition, { entity, relations }); - } - - openMetricInfo(event: Event, matButton: MatIconButton, metric: SolutionDescriptorMetric): void { - this.openInfoPopover(event, matButton, MetricInfoPanelComponent, true, { metric }); - } - - openIamInfo(event: Event, matButton: MatIconButton, iam: SolutionDescriptorIam): void { - this.openInfoPopover(event, matButton, IamInfoPanelComponent, true, { iam }); - } - - deleteAlarm($event: Event, alarm: SolutionDescriptorAlarm): void { - $event?.stopPropagation(); - this.dialog.confirm( - this.translate.instant('solution-creator.delete-alarm-title'), - this.translate.instant('solution-creator.delete-alarm-text'), - null, - this.translate.instant('action.delete') - ).subscribe((value) => { - if (value) { - const updated = { ...this.description, alarms: this.description.alarms.filter(item => item !== alarm) }; - this.updatedDescription.emit(updated); - } - }); - } - - updatedSolutionDescriptor($event: MouseEvent) { - $event?.stopPropagation(); - this.solutionDescriptor.markAsPristine(); - this.updatedDescription.emit(this.solutionDescriptor.value); - } - - private openInfoPopover(event: Event, ref: MatIconButton | HTMLElement, componentType: Type, fixedPosition: boolean, - context: Record): void { - event?.stopPropagation(); - const trigger = ref instanceof HTMLElement ? ref : ref._elementRef.nativeElement; - if (this.popoverService.hasPopover(trigger)) { - this.popoverService.hidePopover(trigger); - } else { - this.popoverService.displayPopover({ - trigger, - renderer: this.renderer, - componentType, - hostView: this.viewContainerRef, - preferredPlacement: fixedPosition - ? ['leftTopOnly', 'leftOnly', 'leftBottomOnly'] - : StrictPopoverPlacements as any, - context, - showCloseButton: true, - overlayStyle: {maxHeight: '80vh', height: '100%'} - }); - } - } - - private prepareEntityToDatasource(type: string) { - const findEntity = this.solutionEntities.find(entity => entity.value === type); - this.solutionEntityTitle = findEntity?.fullTitle ?? findEntity?.title ?? ''; - switch (type) { - case 'entityProfiles': - this.displayedColumns = ['name', 'entityType', 'telemetry', 'entityActions']; - this.dataSource.loadData(this.prepareEntityProfiles()); - break; - case 'metrics': - this.displayedColumns = ['calculatedFieldName', 'profileName', 'metricActions']; - this.dataSource.loadData(this.description.metrics); - break; - case 'alarms': - this.displayedColumns = ['alarmName', 'profileNames', 'severities', 'alarmActions']; - this.dataSource.loadData(this.description.alarms); - break; - case 'iam': - this.displayedColumns = ['name', 'permissions', 'iamActions']; - this.dataSource.loadData(this.description.iam); - break; - default: - this.dataSource.loadData([]); - } - } - - private prepareEntityProfiles(): SolutionDescriptorEntityBase[] { - const data: SolutionDescriptorEntityBase[] = []; - Object.values(this.description.entityProfiles).forEach((entities: SolutionEntity[]) => { - entities.forEach((entity: SolutionEntity) => { - data.push(entity); - }) - }); - return data; - } - - private prepareSchemaData() { - this.links = []; - this.nodes = []; - this.clusters = []; - - const slug = (s: string) => - s.toLowerCase().normalize('NFKD') - .replace(/[\u0300-\u036f]/g, '') - .replace(/\s+/g, '-') - .replace(/[^a-z0-9_-]/g, '-') - .replace(/-+/g, '-') - .replace(/^-+|-+$/g, ''); - - const cssSafeId = (base: string) => { - const v = slug(base); - return v && !/^[a-z_]/.test(v) ? `n-${v}` : (v || 'n'); - }; - - const nodeIdOf = (type: string, name: string) => - `n-${cssSafeId(type)}__${cssSafeId(name)}`; - - const linkIdOf = (sourceNodeId: string, targetNodeId: string, label?: string) => - `e-${sourceNodeId}__to__${targetNodeId}${label ? `__${cssSafeId(label)}` : ''}`; - - const nodeByName = new Map(); - const nodeIdSet = new Set(); - const linkIdSet = new Set(); - const clusterByScope = new Map(); - const ensureCluster = (scope?: string | null) => { - if (!scope) return undefined; - if (!clusterByScope.has(scope)) { - const id = `c-${cssSafeId(scope)}`; - const clusterNode = { id, label: scope, childNodeIds: [] }; - clusterByScope.set(scope, clusterNode); - this.clusters.push(clusterNode); - } - return clusterByScope.get(scope); - }; - - const addNode = (entity: SolutionDescriptorEntityBase) => { - const id = nodeIdOf(entity.entityType || 'Entity', entity.name || 'Unnamed'); - if (nodeIdSet.has(id)) return id; - - const node: Node = { - id, - label: entity.name || 'Unnamed', - dimension: { - width: 200, - height: 56 - }, - data: { - entityType: entity.entityType || 'Entity', - scope: entity.scope, - entity - } - }; - - const scope = entity.entityType === 'Customer' ? entity.name : entity.scope; - const cluster = ensureCluster(scope); - if (cluster) { - cluster.childNodeIds?.push(id); - } - - this.nodes.push(node); - nodeIdSet.add(id); - nodeByName.set(entity.name, node); - return id; - }; - - const pushLink = (sourceId: string, targetId: string, label?: string) => { - const lbl = (label || '').trim(); - const id = linkIdOf(sourceId, targetId, lbl || undefined); - if (linkIdSet.has(id)) return; - this.links.push({ id, source: sourceId, target: targetId, label: lbl || undefined }); - linkIdSet.add(id); - }; - - const allProfiles: SolutionDescriptorEntityBase[] = Object.values(this.prepareEntityProfiles()).flat(); - - for (const entity of allProfiles) { - addNode(entity); - } - - for (const relation of this.description.relations) { - const fromNode = nodeByName.get(relation.parent); - const toNode = nodeByName.get(relation.child); - if (fromNode && toNode) { - const label = `${relation.type || ''}${relation.cardinality ? ` (${relation.cardinality})` : ''}`.trim(); - pushLink(fromNode.id, toNode.id, label || undefined); - } - } - - const byType = (t: string) => - allProfiles.filter(x => (x.entityType || '').toLowerCase() === t.toLowerCase()); - const tenantUsers = byType('User').filter(x => x.scope === 'Tenant'); - const customers = byType('Customer'); - const assets = byType('Asset'); - const devices = byType('Device'); - const customerUsers = byType('User').filter(x => x.scope !== 'Tenant'); - - // Tenant -> Customer (manages), if both exist - for (const t of tenantUsers) { - const tId = nodeByName.get(t.name)?.id; - if (!tId) continue; - for (const c of customers) { - if (!this.description.relations.some(x => x.child === c.name)) { - const cId = nodeByName.get(c.name)?.id; - if (cId) pushLink(tId, cId, 'Manages'); - } - } - } - - // Customer -> Asset (owns) when scope aligns - for (const c of customers) { - const cId = nodeByName.get(c.name)?.id; - if (!cId) continue; - for (const a of assets) { - if (a.scope === c.name || a.scope === c.scope) { - if (!this.description.relations.some(x => x.child === a.name)) { - const aId = nodeByName.get(a.name)?.id; - if (aId) pushLink(cId, aId, 'Own'); - } - } - } - } - - // Customer -> Device (owns) when scope aligns - for (const c of customers) { - const cId = nodeByName.get(c.name)?.id; - if (!cId) continue; - for (const d of devices) { - if (d.scope === c.name || d.scope === c.scope) { - if (!this.description.relations.some(x => x.child === d.name)) { - const aId = nodeByName.get(d.name)?.id; - if (aId) pushLink(cId, aId, 'Own'); - } - } - } - } - - // Customer -> User (role) when scope aligns - for (const c of customers) { - const cId = nodeByName.get(c.name)?.id; - if (!cId) continue; - for (const u of customerUsers) { - if (u.scope === c.name || u.scope === c.scope) { - if (!this.description.relations.some(x => x.child === u.name)) { - const uId = nodeByName.get(u.name)?.id; - if (uId) pushLink(cId, uId, 'Manages'); - } - } - } - } - } -} - - -class EntityOverviewDatasource extends TbTableDatasource { -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview.scss b/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview.scss deleted file mode 100644 index 8650103bda..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/solution/overview/solution-creator-overview.scss +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - .tb-solution-settings { - z-index: 2; - display: flex; - flex: 1; - flex-direction: column; - min-width: 0; - min-height: 0; - overflow: hidden; - border-left: 1px solid rgba(0, 0, 0, 0.12); - - .tb-solution-settings-toolbar { - height: 50px; - min-height: 50px; - padding: 0 12px; - justify-content: space-between; - --mat-toolbar-container-background-color: #fff; - --mat-toolbar-title-text-size: 18px; - border-bottom: 1px solid rgba(0, 0, 0, 0.12); - } - - .tb-solution-settings-container { - padding: 12px; - display: flex; - flex-direction: column; - overflow: hidden; - flex: 1; - gap: 16px; - - .tb-solution-settings-container-setting { - display: flex; - flex: 1; - min-height: 0; - border-radius: 8px; - border: 1px solid rgba(0, 0, 0, 0.12); - overflow: hidden; - - .tb-solution-menu-container { - overflow: auto; - border-right: 1px solid rgba(0, 0, 0, 0.12); - } - - .tb-solution-menu { - padding: 0; - --mat-list-list-item-label-text-weight: 500; - .mdc-list-item { - border-bottom: 1px solid rgba(0, 0, 0, 0.12); - } - .mdc-list-item--selected { - border-bottom-color: var(--tb-primary-500); - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; - } - } - } - } - - &::ng-deep { - tb-json-object-edit .tb-json-object-panel { - margin-left: 0; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html new file mode 100644 index 0000000000..63bead5b6f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html @@ -0,0 +1,34 @@ + +
+ @if (dashboards.length > 1) { +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { + + } +
+ } +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { +
+
+ +
+

{{ dashboard.name }}

+ {{ dashboard.assignedTo }} +
+
+ @if (dashboard.overview) { +

{{ dashboard.overview }}

+ } + +
+ } @empty { +

{{ 'solution-creator.pane.no-dashboards' | translate }}

+ } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss new file mode 100644 index 0000000000..ac9767e0fe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-dash { + padding: 16px var(--art-x) 8px; + + & + .sol-dash { + border-top: 1px solid var(--tb-line); + } +} + +.sol-dash-head { + display: flex; + align-items: flex-start; + gap: 10px; + + > .mat-icon { + flex: none; + margin-top: 2px; + color: var(--entity-view-fg); + } + + h3 { + margin: 0; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } +} + +.sol-dash-lead { + margin: 10px 0 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-dash-doc { + display: block; + margin-top: 4px; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts new file mode 100644 index 0000000000..bb1e85849a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, Component, ElementRef, inject, Input, OnDestroy, signal } from '@angular/core'; +import { DashboardsOverview } from '@shared/models/solution-creator.models'; + +@Component({ + selector: 'tb-solution-dashboards', + templateUrl: './solution-dashboards.component.html', + styleUrls: ['./solution-pane.scss', './solution-dashboards.component.scss'], + standalone: false +}) +export class SolutionDashboardsComponent implements AfterViewInit, OnDestroy { + + @Input({required: true}) dashboards: DashboardsOverview[] = []; + + readonly markdownStyles = [ + '.tb-markdown-view h1, .tb-markdown-view h2, .tb-markdown-view h3 { display: none; }', + '.tb-markdown-view h4, .tb-markdown-view h5 { font-size: 14px; line-height: 20px; font-weight: 500; margin: 16px 0 6px; padding: 0; }', + '.tb-markdown-view p, .tb-markdown-view li { font-size: 14px; line-height: 20px; padding: 0; }', + '.tb-markdown-view ul, .tb-markdown-view ol { padding-left: 20px; margin: 0; }' + ]; + + active = signal(0); + + wide = signal(false); + + private host = inject>(ElementRef); + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.onScroll(); + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660 && this.dashboards?.length > 1)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.sol-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + goTo(index: number): void { + this.active.set(index); + const target = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (target && this.scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + this.scroller.scrollTo({ + top: this.scroller.scrollTop + target.getBoundingClientRect().top - this.scroller.getBoundingClientRect().top - tabs, + behavior: 'smooth' + }); + } + } + + private onScroll(): void { + if (!this.scroller) { + return; + } + const top = this.scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current = 0; + this.dashboards.forEach((_, index) => { + const el = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = index; + } + }); + if (current !== this.active()) { + this.active.set(current); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html new file mode 100644 index 0000000000..45d1200b9a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html @@ -0,0 +1,82 @@ + +@if (installed() && !bannerClosed()) { +
+ +
+ {{ 'solution-creator.pane.installed' | translate }} + {{ 'solution-creator.pane.installed-line' | translate: {entities: entityCount(), dashboards: dashboardCount()} }} +
+ @if (hasMain()) { + + } + +
+} @else if (!installed()) { +

{{ 'solution-creator.pane.not-installed' | translate }}

+} +
+ @for (section of sections(); track section.type) { +

{{ section.title | translate }}

+ + + @for (row of section.rows; track row.key) { + + + + @if (section.type === 'DASHBOARD') { + + } + + + } + +
+ + + @if (link(section.type, row); as url) { + {{ row.primary.additionalData?.name }} + } @else { + {{ row.primary.additionalData?.name }} + } + + + @if (section.type === 'ALARM' && severities(row).length) { + @for (severity of severities(row); track severity) { + {{ severityLabel(severity) | translate }} + } + } + {{ detail(section.type, row) }} + + @if (link(section.type, row); as url) { + + open_in_new + + } + @if (canViewAs(row)) { + + } + + + {{ statusIcon(row) }} + +
+ } @empty { +

{{ 'solution-creator.pane.nothing-created' | translate }}

+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss new file mode 100644 index 0000000000..a4bcb75625 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-done { + position: sticky; + top: 0; + z-index: 2; + display: flex; + align-items: center; + gap: 16px; + padding: 22px calc(var(--art-x) + 36px) 22px var(--art-x); + background: linear-gradient(90deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 42%, var(--tb-surface)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 26%, var(--tb-surface)) 48%, + var(--tb-surface) 100%); +} + +.sol-done-mark { + --ai-mark-fill: linear-gradient(var(--tb-surface), var(--tb-surface)); + --ai-mark-edge: inset 0 0 0 1px color-mix(in srgb, var(--tb-ink) 10%, transparent), 0 1px 2px rgb(16 24 40 / 0.06); + --ai-mark-ink: var(--tb-ok); + --ai-mark-ink-fill: linear-gradient(var(--tb-ok), var(--tb-ok)); + animation: none; +} + +.sol-done-t { + flex: 1; + display: grid; + gap: 2px; + min-width: 0; + + b { + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + span { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } +} + +.sol-done-go { + flex: none; + --mat-button-filled-container-color: var(--ai-action); + --mdc-filled-button-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); + --mdc-filled-button-label-text-color: var(--ai-on-action); +} + +.sol-done-x { + position: absolute; + top: 8px; + right: 8px; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } +} + +.sol-not-installed { + margin: 0; + padding: 16px var(--art-x) 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-installed-table { + table-layout: fixed; + + td.sol-installed-name { + width: 44%; + } + + td.act { + width: 76px; + } + + td.stc { + width: 44px; + } +} + +.sol-act { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + margin: -6px 0 -6px 2px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-60); + cursor: pointer; + vertical-align: top; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-st { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 18px; + height: 18px; + margin-top: 1px; + border-radius: 50%; + color: var(--tb-surface); + cursor: default; + + .mat-icon { + font-size: 13px; + width: 13px; + height: 13px; + line-height: 13px; + font-weight: 500; + } + + &.ok { background: var(--tb-ok); } + &.warn { background: var(--tb-caution); } + &.error { background: var(--tb-crit); } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts new file mode 100644 index 0000000000..3e443654cf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AuthService } from '@core/auth/auth.service'; +import { EntityResult, SolutionCreatorInfo } from '@shared/models/solution-creator.models'; +import { + baseDetailsPageByEntityType, + EntityType, + entityTypeTranslations, + groupUrlPrefixByEntityType +} from '@shared/models/entity-type.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { + AggregatedEntityResult, + aggregateByName, + IssueStatus +} from '@home/components/ai/solution/solution-info/issues-aggregation'; + +interface InstalledSection { + type: EntityType; + title: string; + icon: string; + palette: string; + rows: AggregatedEntityResult[]; +} + +const SECTIONS: EntityType[] = [ + EntityType.DASHBOARD, + EntityType.DEVICE, + EntityType.ASSET, + EntityType.CUSTOMER, + EntityType.USER, + EntityType.DEVICE_PROFILE, + EntityType.ASSET_PROFILE, + EntityType.ROLE, + EntityType.ENTITY_GROUP, + EntityType.CALCULATED_FIELD, + EntityType.ALARM, + EntityType.RULE_CHAIN +]; + +@Component({ + selector: 'tb-solution-installed', + templateUrl: './solution-installed.component.html', + styleUrls: ['./solution-pane.scss', './solution-installed.component.scss'], + standalone: false +}) +export class SolutionInstalledComponent { + + solution = input.required(); + + @Output() openMain = new EventEmitter(); + + private translate = inject(TranslateService); + private authService = inject(AuthService); + + bannerClosed = signal(false); + + installed = computed(() => !!this.solution()?.metadata?.installed); + + sections = computed(() => { + const results = this.solution()?.metadata?.installResult?.entityResults; + if (!results) { + return []; + } + return SECTIONS + .map(type => { + const kind = aiEntityKind(type === EntityType.ALARM ? 'ALARM_RULE' : type); + return { + type, + title: entityTypeTranslations.get(type)?.typePlural ?? type, + icon: kind.icon, + palette: kind.palette, + rows: aggregateByName(type, results[type]) + }; + }) + .filter(section => section.rows.length); + }); + + entityCount = computed(() => this.sections() + .filter(section => section.type !== EntityType.DASHBOARD) + .reduce((count, section) => count + section.rows.length, 0)); + + dashboardCount = computed(() => this.sections().find(section => section.type === EntityType.DASHBOARD)?.rows.length ?? 0); + + hasMain = computed(() => !!this.solution()?.metadata?.installResult?.mainDashboardId); + + link(type: EntityType, row: AggregatedEntityResult): string | null { + const entity = row.primary; + if (!entity?.id?.id || row.status === IssueStatus.ERROR) { + return null; + } + if (type === EntityType.ENTITY_GROUP) { + const prefix = groupUrlPrefixByEntityType.get(entity.additionalData?.groupType as EntityType); + return prefix ? `${prefix}/${entity.id.id}` : null; + } + const base = baseDetailsPageByEntityType.get(entity.id.entityType as EntityType); + return base ? `${base}/${entity.id.id}` : null; + } + + detail(type: EntityType, row: AggregatedEntityResult): string { + const data = row.primary?.additionalData; + switch (type) { + case EntityType.DASHBOARD: + return this.userName(data?.userId); + case EntityType.USER: + return [data?.customer || this.translate.instant('tenant.tenant'), data?.email].filter(Boolean).join(' · '); + case EntityType.ALARM: + return data?.condition ?? ''; + case EntityType.ENTITY_GROUP: + return data?.groupType ? this.translate.instant(entityTypeTranslations.get(data.groupType as EntityType)?.typePlural ?? data.groupType) : ''; + default: + return data?.type ?? data?.customer ?? ''; + } + } + + severities(row: AggregatedEntityResult): AlarmSeverity[] { + return row.primary?.additionalData?.severities ?? []; + } + + severityColor(severity: AlarmSeverity): string { + return alarmSeverityColors.get(severity) ?? null; + } + + severityLabel(severity: AlarmSeverity): string { + return alarmSeverityTranslations.get(severity) ?? severity; + } + + statusIcon(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'close' : row.status === IssueStatus.WARN ? 'priority_high' : 'check'; + } + + statusTone(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'error' : row.status === IssueStatus.WARN ? 'warn' : 'ok'; + } + + statusTip(row: AggregatedEntityResult): string { + const word = this.translate.instant('solution-creator.pane.status-' + this.statusTone(row)); + const messages = [...row.errors, ...row.warnings].map(entry => entry.error?.message).filter(Boolean); + return messages.length ? `${word}: ${messages.join('; ')}` : word; + } + + canViewAs(row: AggregatedEntityResult): boolean { + return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR; + } + + viewAs(row: AggregatedEntityResult): void { + const entity: EntityResult = row.primary; + const userId = entity.additionalData.userId; + const tenantUser = !this.findUser(userId)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${entity.id.id}` : `/dashboards/${entity.id.id}`; + this.authService.loginAsUser(userId).subscribe(() => {}); + } + + private userName(userId: string | undefined): string { + return userId ? this.findUser(userId)?.additionalData?.name ?? '' : ''; + } + + private findUser(userId: string): EntityResult | undefined { + return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html new file mode 100644 index 0000000000..1282a24c4a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html @@ -0,0 +1,268 @@ + +
+
+ @for (section of sections(); track section.id) { + + } +
+
+
+

{{ 'solution-creator.pane.profiles' | translate }}

+
+ + +
+
+ @if (mode() === 'list') { + + + + + + + + + + + @for (profile of profiles; track profile.name + profile.entityType) { + @let key = 'profile:' + profile.entityType + ':' + profile.name; + + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.type' | translate }}{{ 'solution-creator.pane.data' | translate }}
+ + {{ profile.name }} + + {{ typeLabel(profile) }}{{ dataOf(profile) }}expand_more
+ +
+ } @else { +
+ + + + + + + + + + {{ cluster.label }} + + + + + + + + + + + @if (link.label) { + +
{{ link.label }}
+
+ } +
+
+
+
+ @if (schemaEntity(); as entity) { +
+
+ {{ entity.name }} +
+ +
+ } + } + +

{{ 'solution-creator.pane.roles' | translate }}

+ @if (descriptor?.iam?.length) { + + + + + + + + + + @for (iam of descriptor.iam; track iam.name) { + + + + + + } + +
{{ 'solution-creator.pane.role' | translate }}{{ 'solution-creator.pane.operations' | translate }}{{ 'solution-creator.pane.on' | translate }}
+ {{ iam.name }} + + @for (operation of operations(iam); track operation) { + {{ ('solution-creator.pane.op-' + operation) | translate }} + } @empty { + {{ iam.permissions || '—' }} + } + {{ iam.description }}
+ } @else { +

{{ 'solution-creator.pane.no-roles' | translate }}

+ } + +

{{ 'solution-creator.pane.calculated-fields' | translate }}

+ @if (descriptor?.metrics?.length) { + + + + + + + + + @for (metric of descriptor.metrics; track metric.calculatedFieldName) { + + + + + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.calculates' | translate }}
+ + + {{ metric.calculatedFieldName }}{{ metric.profileName }} + + {{ metric.calculation }}
+ } @else { +

{{ 'solution-creator.pane.no-calculated-fields' | translate }}

+ } + +

{{ 'solution-creator.pane.alarms' | translate }}

+ @if (descriptor?.alarms?.length) { + + + + + + + + + + @for (alarm of descriptor.alarms; track alarm.alarmName) { + @let key = alarmKey(alarm); + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.severity' | translate }}
+ + + {{ alarm.alarmName }}{{ alarm.condition }} + + + @for (severity of alarm.severities; track severity) { + {{ severityLabel(severity) | translate }} + } + expand_more
+
+
{{ 'solution-creator.pane.profiles' | translate }}
+
{{ alarm.profileNames?.join(', ') }}
+
{{ 'solution-creator.pane.condition' | translate }}
+
{{ alarm.condition }}
+
+ +
+ } @else { +

{{ 'solution-creator.pane.no-alarms' | translate }}

+ } +
+
+ + +
+ @if (profile.scope) { +
{{ 'solution-creator.pane.scope' | translate }}
+
{{ profile.scope }}
+ } + @if (profile.description) { +
{{ 'solution-creator.pane.description' | translate }}
+
{{ profile.description }}
+ } +
+
+ + +
+ @if (keysOf() === 'telemetry') { +
    + @for (item of profile.telemetry ?? []; track item.key) { +
  • + {{ item.key }} + {{ (item.telemetryType === 'ATTRIBUTE' ? 'solution-creator.pane.attribute' : 'solution-creator.pane.time-series') | translate }} + @if (item.calculatedFieldName) { + ƒx + } + {{ item.dataType }}{{ item.units ? ' · ' + item.units : '' }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-keys' | translate }}
  • + } +
+ } @else { +
    + @for (relation of relationsOf(profile); track $index) { +
  • + {{ relation.parent }} + {{ relation.type }}{{ relation.cardinality ? ' (' + relation.cardinality + ')' : '' }} + {{ relation.child }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-relations' | translate }}
  • + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss new file mode 100644 index 0000000000..f23f0ea550 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-schema { + height: 380px; + margin: 0 var(--art-x); + overflow: hidden; + + .sol-graph { + display: block; + width: 100%; + height: 100%; + } + + ::ng-deep { + .sol-band rect { + fill: color-mix(in oklab, var(--ai-light-lilac) 34%, var(--tb-surface)); + } + + .sol-band.tenant rect { + fill: color-mix(in oklab, var(--ai-light-peach) 40%, var(--tb-surface)); + } + + .sol-band-title { + font: 400 12px var(--tb-font); + fill: var(--tb-ink-60); + } + + .sol-edge .line { + stroke: var(--tb-ink-38); + fill: none; + } + + .sol-arrow-head { + fill: var(--tb-ink-38); + } + + .sol-edge-label { + width: fit-content; + max-width: 120px; + margin: 0 auto; + padding: 1px 6px; + border: 1px solid var(--tb-line); + border-radius: 4px; + background: var(--tb-surface); + font: 400 12px/18px var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; + } + + .sol-box { + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + padding: 8px 12px; + box-sizing: border-box; + border: 1px solid var(--tb-line); + border-left: 3px solid var(--tb-ink-38); + border-radius: 8px; + background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06); + text-align: left; + cursor: pointer; + font-family: var(--tb-font); + + b { + font: 500 14px/18px var(--tb-font); + color: var(--tb-ink); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + span { + font: 400 12px/16px var(--tb-font); + color: var(--tb-ink-60); + } + + &[data-pal="device"] { border-left-color: var(--entity-device-fg); } + &[data-pal="people"] { border-left-color: var(--entity-people-fg); } + &[data-pal="solution"] { border-left-color: var(--entity-solution-fg); } + &[data-pal="path"] { border-left-color: var(--entity-path-fg); } + + &:hover, &.on { + border-color: var(--tb-ink-38); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } + } +} + +.sol-schema-detail { + margin: 12px var(--art-x) 0; + padding: 12px 14px 14px; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts new file mode 100644 index 0000000000..bef97facf8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + Component, + computed, + ElementRef, + EventEmitter, + inject, + Input, + OnChanges, + OnDestroy, + Output, + signal, + ViewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { ClusterNode, Edge, GraphComponent, Node } from '@swimlane/ngx-graph'; +import { DialogService } from '@core/services/dialog.service'; +import { + SolutionDescriptor, + SolutionDescriptorAlarm, + SolutionDescriptorEntityBase, + SolutionDescriptorEntityBaseRelation, + SolutionDescriptorIam +} from '@shared/models/solution-creator.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { buildSolutionSchema } from '@home/components/ai/solution/pane/solution-schema'; + +type SectionId = 'profiles' | 'roles' | 'metrics' | 'alarms'; + +interface Section { + id: SectionId; + title: string; +} + +const OPERATIONS: Record = {C: 'create', R: 'read', U: 'update', D: 'delete'}; + +@Component({ + selector: 'tb-solution-overview', + templateUrl: './solution-overview.component.html', + styleUrls: ['./solution-pane.scss', './solution-overview.component.scss'], + standalone: false +}) +export class SolutionOverviewComponent implements OnChanges, AfterViewInit, OnDestroy { + + @Input({required: true}) descriptor: SolutionDescriptor; + + @Output() descriptorChange = new EventEmitter(); + + @ViewChild('graphContainer') graphContainer: ElementRef; + @ViewChild(GraphComponent) graphComponent: GraphComponent; + + private translate = inject(TranslateService); + private dialog = inject(DialogService); + private host = inject>(ElementRef); + + mode = signal<'list' | 'schema'>('list'); + open = signal(null); + keysOf = signal<'telemetry' | 'relations'>('telemetry'); + active = signal('profiles'); + wide = signal(false); + + profiles: SolutionDescriptorEntityBase[] = []; + nodes: Node[] = []; + links: Edge[] = []; + clusters: ClusterNode[] = []; + + sections = computed(() => [ + {id: 'profiles', title: 'solution-creator.pane.profiles'}, + {id: 'roles', title: 'solution-creator.pane.roles'}, + {id: 'metrics', title: 'solution-creator.pane.calculated-fields'}, + {id: 'alarms', title: 'solution-creator.pane.alarms'} + ]); + + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.scroller && this.onScroll(this.scroller); + private graphResize: ResizeObserver; + + ngOnChanges(): void { + this.profiles = this.descriptor ? Object.values(this.descriptor.entityProfiles ?? {}).flat() as SolutionDescriptorEntityBase[] : []; + if (this.mode() === 'schema') { + this.buildSchema(); + } + } + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.sol-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.graphResize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + severityColor(severity: string): string { + return alarmSeverityColors.get(severity?.toUpperCase() as AlarmSeverity) ?? null; + } + + severityLabel(severity: string): string { + return alarmSeverityTranslations.get(severity?.toUpperCase() as AlarmSeverity) ?? severity; + } + + setMode(mode: 'list' | 'schema'): void { + this.mode.set(mode); + if (mode === 'schema') { + this.buildSchema(); + requestAnimationFrame(() => this.observeGraph()); + } + } + + toggle(key: string): void { + this.open.set(this.open() === key ? null : key); + this.keysOf.set('telemetry'); + } + + goTo(section: SectionId): void { + this.active.set(section); + const target = this.host.nativeElement.querySelector(`[data-sec="${section}"]`) as HTMLElement; + const scroller = this.host.nativeElement.closest('.sol-pane-body') as HTMLElement; + if (target && scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + scroller.scrollTo({top: scroller.scrollTop + target.getBoundingClientRect().top - scroller.getBoundingClientRect().top - tabs, behavior: 'smooth'}); + } + } + + onScroll(scroller: HTMLElement): void { + const top = scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current: SectionId = 'profiles'; + for (const section of this.sections()) { + const el = this.host.nativeElement.querySelector(`[data-sec="${section.id}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = section.id; + } + } + if (current !== this.active()) { + this.active.set(current); + } + } + + kind(entity: SolutionDescriptorEntityBase): {icon: string; palette: string} { + return aiEntityKind((entity.entityType ?? '').toUpperCase()); + } + + typeLabel(entity: SolutionDescriptorEntityBase): string { + const type = (entity.entityType ?? '').toLowerCase(); + return type ? type.charAt(0).toUpperCase() + type.slice(1) : ''; + } + + relationsOf(entity: SolutionDescriptorEntityBase): SolutionDescriptorEntityBaseRelation[] { + return (this.descriptor?.relations ?? []).filter(relation => relation.parent === entity.name || relation.child === entity.name); + } + + dataOf(entity: SolutionDescriptorEntityBase): string { + const keys = entity.telemetry?.length ?? 0; + const relations = this.relationsOf(entity).length; + const parts = []; + if (keys) { + parts.push(this.translate.instant('solution-creator.pane.keys', {count: keys})); + } + if (relations) { + parts.push(this.translate.instant('solution-creator.pane.relations', {count: relations})); + } + return parts.join(' · ') || '—'; + } + + operations(iam: SolutionDescriptorIam): string[] { + return (iam.permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]); + } + + alarmKey(alarm: SolutionDescriptorAlarm): string { + return 'alarm:' + alarm.alarmName; + } + + removeAlarm(alarm: SolutionDescriptorAlarm): void { + this.dialog.confirm( + this.translate.instant('solution-creator.delete-alarm-title'), + this.translate.instant('solution-creator.delete-alarm-text'), + null, + this.translate.instant('action.delete') + ).subscribe(confirmed => { + if (confirmed) { + this.open.set(null); + this.descriptorChange.emit({...this.descriptor, alarms: this.descriptor.alarms.filter(item => item !== alarm)}); + } + }); + } + + openFromSchema(node: Node): void { + const entity = node.data?.entity as SolutionDescriptorEntityBase; + if (entity) { + this.open.set(this.open() === 'schema:' + entity.name ? null : 'schema:' + entity.name); + } + } + + schemaEntity(): SolutionDescriptorEntityBase | undefined { + const key = this.open(); + return key?.startsWith('schema:') ? this.profiles.find(profile => 'schema:' + profile.name === key) : undefined; + } + + private buildSchema(): void { + const schema = buildSolutionSchema(this.descriptor, this.profiles); + this.nodes = schema.nodes; + this.links = schema.links; + this.clusters = schema.clusters; + } + + private observeGraph(): void { + this.graphResize?.disconnect(); + if (this.graphContainer?.nativeElement) { + this.graphResize = new ResizeObserver(() => this.graphComponent?.basicUpdate()); + this.graphResize.observe(this.graphContainer.nativeElement); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss new file mode 100644 index 0000000000..4ff3608ce0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss @@ -0,0 +1,407 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + --art-x: 16px; + display: block; + min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} + +.art-seg { + flex: none; + display: inline-flex; + padding: 3px; + border-radius: 999px; + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + + button { + height: 26px; + padding: 0 12px; + border: 0; + border-radius: 999px; + background: none; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--ai-action); + color: var(--ai-on-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +.sol-paged { + display: flex; + flex-direction: column; + + &.wide { + display: grid; + grid-template-columns: 168px minmax(0, 1fr); + align-items: start; + + > .sol-tabs { + position: sticky; + top: 0; + flex-direction: column; + align-items: stretch; + gap: 2px; + padding: 12px 8px 12px var(--art-x); + border-bottom: 0; + overflow: visible; + + button { + display: block; + margin: 0; + padding: 6px 10px; + border: 0; + border-left: 2px solid transparent; + border-radius: 0 6px 6px 0; + white-space: normal; + + &[aria-selected="true"] { + border-left-color: var(--ai-action); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } + + &:hover { + background: color-mix(in srgb, var(--tb-ink) 3%, transparent); + } + } + } + } +} + +.sol-tabs { + position: sticky; + top: 0; + z-index: 2; + display: flex; + gap: 2px; + padding: 6px max(0px, calc(var(--art-x) - 6px)) 0; + border-bottom: 1px solid var(--tb-line); + background: var(--tb-surface); + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + + button { + flex: none; + padding: 6px 6px 8px; + border: 0; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-60); + text-align: left; + cursor: pointer; + white-space: nowrap; + + &:hover { + color: var(--tb-ink); + } + + &[aria-selected="true"] { + color: var(--tb-ink); + border-bottom-color: var(--ai-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: -2px; + border-radius: 6px; + } + } +} + +.sol-infos { + min-width: 0; + padding: 4px 0 16px; +} + +.sol-sec-head { + display: flex; + align-items: center; + gap: 12px; + min-height: 52px; + padding: 14px var(--art-x) 6px; + box-sizing: border-box; + + h3 { + flex: 1; + margin: 0; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } +} + +.sol-empty { + margin: 0; + padding: 4px var(--art-x) 12px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--k-faint); +} + +table.sol-table { + width: 100%; + border-collapse: collapse; + border-spacing: 0; + + th { + height: 30px; + padding: 0 10px 0 0; + font: 400 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .2px; + color: var(--k-faint); + text-align: left; + border-bottom: 1px solid var(--tb-line); + } + + td { + min-width: 72px; + height: 40px; + padding: 9px 10px 9px 0; + box-sizing: border-box; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: 0; + color: var(--tb-ink); + border-bottom: 1px solid var(--tb-line); + vertical-align: top; + } + + th:first-child, td:first-child { + padding-left: var(--art-x); + } + + th:last-child, td:last-child { + padding-right: var(--art-x); + } + + .secondary { + color: var(--tb-ink-76); + } + + .faint { + color: var(--k-faint); + } + + .wrap { + white-space: normal; + overflow-wrap: break-word; + } + + .nowrap { + white-space: nowrap; + } + + .chev, .stc, .act { + width: 1px; + white-space: nowrap; + text-align: right; + } + + tbody tr.clickable { + cursor: pointer; + + &:hover td { + background: color-mix(in srgb, var(--tb-ink) 2.5%, transparent); + } + } + + tbody tr.on td { + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + border-bottom-color: transparent; + } + + tr.sol-exp td { + height: auto; + padding: 0 var(--art-x) 14px calc(var(--art-x) + 26px); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } +} + +.sol-chev { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-38); + transition: transform .15s ease; + + &.open { + transform: rotate(180deg); + } +} + +.sol-name { + display: flex; + align-items: flex-start; + gap: 8px; + min-width: 0; + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-54); + } + + &[data-pal="device"] > .mat-icon { color: var(--entity-device-fg); } + &[data-pal="people"] > .mat-icon { color: var(--entity-people-fg); } + &[data-pal="path"] > .mat-icon { color: var(--entity-path-fg); } + &[data-pal="rule"] > .mat-icon { color: var(--entity-rule-fg); } + &[data-pal="view"] > .mat-icon { color: var(--entity-view-fg); } + &[data-pal="chain"] > .mat-icon { color: var(--entity-chain-fg); } + &[data-pal="solution"] > .mat-icon { color: var(--entity-solution-fg); } + + b { + font-weight: 500; + min-width: 0; + overflow-wrap: break-word; + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } + + a { + color: var(--tb-ink); + border-bottom: 0 !important; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + transition: text-decoration-color .15s ease; + + &:hover { + text-decoration-color: var(--tb-ink-54); + } + } +} + +.sol-op { + display: inline-block; + margin: 0 4px 4px 0; + padding: 0 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.05); + font-size: var(--chat-meta); + line-height: 20px; + color: var(--tb-ink-76); +} + +.sol-sev { + display: inline-flex; + align-items: center; + gap: 5px; + margin-right: 8px; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + font-weight: 500; + white-space: nowrap; + + i { + width: 7px; + height: 7px; + border-radius: 50%; + background: currentColor; + } +} + +.sol-facts { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 2px 16px; + margin: 0; + padding: 10px 0 0; + + dt { + color: var(--tb-ink-60); + } + + dd { + margin: 0; + color: var(--tb-ink); + } +} + +.sol-keys-seg { + margin: 12px 0 8px; +} + +.sol-keys { + list-style: none; + margin: 0; + padding: 0; + display: grid; + + li { + display: flex; + align-items: baseline; + gap: 8px; + padding: 4px 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + li + li { + border-top: 1px solid var(--tb-line); + } +} + +.sol-key { + padding: 1px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: 20px; + color: var(--tb-ink); +} + +.sol-key-type, .sol-key-dt { + color: var(--k-faint); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); +} + +.sol-key-fx { + color: var(--entity-path-fg); + font-style: italic; + font-size: var(--chat-meta); +} + +.sol-key-dt { + margin-left: auto; + white-space: nowrap; +} + +.sol-remove { + margin-top: 10px; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts new file mode 100644 index 0000000000..572887a35a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ClusterNode, Edge, Node } from '@swimlane/ngx-graph'; +import { SolutionDescriptor, SolutionDescriptorEntityBase } from '@shared/models/solution-creator.models'; + +export interface SolutionSchema { + nodes: Node[]; + links: Edge[]; + clusters: ClusterNode[]; +} + +export function buildSolutionSchema(descriptor: SolutionDescriptor, profiles: SolutionDescriptorEntityBase[]): SolutionSchema { + const nodes: Node[] = []; + const links: Edge[] = []; + const clusters: ClusterNode[] = []; + if (!descriptor) { + return {nodes, links, clusters}; + } + + const slug = (s: string) => + s.toLowerCase().normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/\s+/g, '-') + .replace(/[^a-z0-9_-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-+|-+$/g, ''); + + const cssSafeId = (base: string) => { + const v = slug(base); + return v && !/^[a-z_]/.test(v) ? `n-${v}` : (v || 'n'); + }; + + const nodeIdOf = (type: string, name: string) => + `n-${cssSafeId(type)}__${cssSafeId(name)}`; + + const linkIdOf = (sourceNodeId: string, targetNodeId: string, label?: string) => + `e-${sourceNodeId}__to__${targetNodeId}${label ? `__${cssSafeId(label)}` : ''}`; + + const nodeByName = new Map(); + const nodeIdSet = new Set(); + const linkIdSet = new Set(); + const clusterByScope = new Map(); + const ensureCluster = (scope?: string | null) => { + if (!scope) return undefined; + if (!clusterByScope.has(scope)) { + const id = `c-${cssSafeId(scope)}`; + const clusterNode: ClusterNode = { id, label: scope, childNodeIds: [], data: {tone: scope === 'Tenant' ? 'tenant' : 'customer'} }; + clusterByScope.set(scope, clusterNode); + clusters.push(clusterNode); + } + return clusterByScope.get(scope); + }; + + const addNode = (entity: SolutionDescriptorEntityBase) => { + const id = nodeIdOf(entity.entityType || 'Entity', entity.name || 'Unnamed'); + if (nodeIdSet.has(id)) return id; + + const node: Node = { + id, + label: entity.name || 'Unnamed', + dimension: { + width: 200, + height: 56 + }, + data: { + entityType: entity.entityType || 'Entity', + scope: entity.scope, + entity + } + }; + + const scope = entity.entityType === 'Customer' ? entity.name : entity.scope; + const cluster = ensureCluster(scope); + if (cluster) { + cluster.childNodeIds?.push(id); + } + + nodes.push(node); + nodeIdSet.add(id); + nodeByName.set(entity.name, node); + return id; + }; + + const pushLink = (sourceId: string, targetId: string, label?: string) => { + const lbl = (label || '').trim(); + const id = linkIdOf(sourceId, targetId, lbl || undefined); + if (linkIdSet.has(id)) return; + links.push({ id, source: sourceId, target: targetId, label: lbl || undefined }); + linkIdSet.add(id); + }; + + const allProfiles: SolutionDescriptorEntityBase[] = profiles; + + for (const entity of allProfiles) { + addNode(entity); + } + + for (const relation of (descriptor.relations ?? [])) { + const fromNode = nodeByName.get(relation.parent); + const toNode = nodeByName.get(relation.child); + if (fromNode && toNode) { + const label = `${relation.type || ''}${relation.cardinality ? ` (${relation.cardinality})` : ''}`.trim(); + pushLink(fromNode.id, toNode.id, label || undefined); + } + } + + const byType = (t: string) => + allProfiles.filter(x => (x.entityType || '').toLowerCase() === t.toLowerCase()); + const tenantUsers = byType('User').filter(x => x.scope === 'Tenant'); + const customers = byType('Customer'); + const assets = byType('Asset'); + const devices = byType('Device'); + const customerUsers = byType('User').filter(x => x.scope !== 'Tenant'); + + for (const t of tenantUsers) { + const tId = nodeByName.get(t.name)?.id; + if (!tId) continue; + for (const c of customers) { + if (!(descriptor.relations ?? []).some(x => x.child === c.name)) { + const cId = nodeByName.get(c.name)?.id; + if (cId) pushLink(tId, cId, 'Manages'); + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const a of assets) { + if (a.scope === c.name || a.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === a.name)) { + const aId = nodeByName.get(a.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const d of devices) { + if (d.scope === c.name || d.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === d.name)) { + const aId = nodeByName.get(d.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const u of customerUsers) { + if (u.scope === c.name || u.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === u.name)) { + const uId = nodeByName.get(u.name)?.id; + if (uId) pushLink(cId, uId, 'Manages'); + } + } + } + } + return {nodes, links, clusters}; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html index adf884ace7..98f19bdba7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -57,7 +57,7 @@
} @else if (creatorStep()) { -
+
+ @if (showPane() && !paneOpen()) { + + }
- @if (showPane()) { -
+ } + @if (creatorStep() === 'chat' && uninstalledAt(); as at) { +
+ + {{ 'solution-creator.uninstalled-at' | translate: {time: (at | date:'HH:mm')} }} + {{ 'solution-creator.uninstalled-note' | translate }} +
+ } @else if (creatorStep() === 'chat' && installed()) { +
+ + {{ 'solution-creator.installed-already' | translate }} + {{ 'solution-creator.installed-already-note' | translate }}
} @if (work(); as current) { @@ -163,7 +195,9 @@

{{ ('solution-creator.pane.estimate-' + making()) | translate }}

} @else if (json()) { - + } @else { @switch (currentView()) { @case ('overview') { @@ -182,9 +216,10 @@
@if (making()) { {{ work()?.words }} - } @else if (json()) { + } @else if (json() && jsonEditing()) { {{ 'solution-creator.pane.json-note' | translate }} - + + } @else if (currentView() === 'solution' || creatorStep() === 'result') { @if (installed()) { } } @else if (currentView() === 'overview') { - + {{ 'solution-creator.pane.estimate-dashboards' | translate }} } @else { + {{ 'solution-creator.pane.estimate-solution' | translate }} - diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss index 3d38b16d77..14ac06c1d2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -335,6 +335,14 @@ } } +.sol-hint { + margin-top: 14px; +} + +.sol-closing .sol-chips { + margin-top: 14px; +} + .sol-work { margin-top: var(--chat-turn-gap, 28px); } @@ -618,10 +626,7 @@ } .sol-json { - display: block; min-height: 0; - padding: 8px 12px; - box-sizing: border-box; } .sol-loading { @@ -695,6 +700,9 @@ .sol-foot-note { flex: 1; min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; font-size: var(--chat-caption); line-height: var(--chat-caption-lh); color: var(--k-faint); diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts index 7ee563c4f8..a595c5d522 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -34,13 +34,14 @@ import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { DialogService } from '@core/services/dialog.service'; import { TranslateService } from '@ngx-translate/core'; import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { AuthService } from '@core/auth/auth.service'; import { SolutionInfoDialogComponent, SolutionInfoDialogData } from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; -import { deepClone, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { FormControl } from '@angular/forms'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; import { EntityId } from '@shared/models/id/entity-id'; @@ -58,6 +59,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private static readonly PANE_MIN = 360; private static readonly CHAT_MIN = 420; private static readonly PANE_WIDTH_KEY = 'tbSolutionPaneWidth'; + private static readonly CONNECTIVITY_GUIDE = 'https://thingsboard.io/docs/getting-started-guides/connectivity/'; @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; @ViewChild(AiChatMessagesComponent) chatMessages: AiChatMessagesComponent; @@ -101,7 +103,27 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe json = signal(false); - jsonControl = new FormControl(null); + jsonEditing = signal(false); + + uninstalledAt = signal(null); + + mainUser = computed<{id: string; name: string} | null>(() => { + const result = this.info()?.metadata?.installResult; + const main = result?.mainDashboardId?.id; + const dashboard = main ? result?.entityResults?.[EntityType.DASHBOARD]?.find(entry => entry.id?.id === main) : undefined; + const userId = dashboard?.additionalData?.userId; + if (!userId) { + return null; + } + const user = result.entityResults?.[EntityType.USER]?.find(entry => entry.id?.id === userId); + return {id: userId, name: user?.additionalData?.name ?? ''}; + }); + + jsonValue = computed(() => this.currentView() === 'dashboards' + ? this.info()?.data?.dashboardsOverview + : this.info()?.data?.solutionDescriptor); + + @ViewChild('jsonView') jsonView: SolutionJsonComponent; paneOpen = signal(typeof window === 'undefined' || window.innerWidth >= SolutionChatComponent.NARROW_WIDTH); @@ -326,7 +348,8 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private dialogService: DialogService, private translate: TranslateService, private sanitizer: DomSanitizer, - private aiSolutions: AiSolutionsService) { + private aiSolutions: AiSolutionsService, + private authService: AuthService) { super(); toObservable(this.activeStepIndex).pipe( @@ -441,6 +464,22 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe }); } + viewAsMainUser(): void { + const user = this.mainUser(); + const main = this.info()?.metadata?.installResult?.mainDashboardId?.id; + if (!user || !main) { + return; + } + const tenantUser = !this.info()?.metadata?.installResult?.entityResults?.[EntityType.USER] + ?.find(entry => entry.id?.id === user.id)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${main}` : `/dashboards/${main}`; + this.authService.loginAsUser(user.id).subscribe(() => {}); + } + + connectDevices(): void { + window.open(SolutionChatComponent.CONNECTIVITY_GUIDE, '_blank', 'noopener'); + } + fillExample(key: string): void { const example = this.solutionExamples.find(ex => ex.key === key); if (example) { @@ -568,6 +607,10 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe ).subscribe((value) => { this.solutionInfo = value; this.aiSolutions.update(this.solutionId, {installed: false}); + this.uninstalledAt.set(Date.now()); + if (this.creatorStep() === 'result') { + this.back(); + } }); } }) @@ -801,6 +844,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private resetSolution(): void { this.clearWork(); + this.uninstalledAt.set(null); this.cancelPending$.next(); this.isReadyStep.set(false); this.skipInterviewAllowed.set(false); @@ -915,18 +959,13 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } toggleJson(): void { - const on = !this.json(); - if (on) { - const data = this.currentView() === 'dashboards' ? this.info()?.data?.dashboardsOverview : this.info()?.data?.solutionDescriptor; - this.jsonControl.setValue(deepClone(data)); - this.jsonControl.markAsPristine(); - } - this.json.set(on); + this.jsonEditing.set(false); + this.json.set(!this.json()); } applyJson(): void { - const value = this.jsonControl.value; - this.jsonControl.markAsPristine(); + const value = this.jsonView?.edited(); + this.jsonView?.done(); if (this.currentView() === 'dashboards') { this.updatedDashboardOverview(value as DashboardsOverview[]); } else { @@ -941,6 +980,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe closePane(): void { this.paneOpen.set(false); this.json.set(false); + this.jsonEditing.set(false); } startResize(event: PointerEvent): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts index 71f1a2e3ea..20cf12a4f9 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts @@ -15,6 +15,7 @@ import { NgxGraphModule } from '@swimlane/ngx-graph'; import { SolutionOverviewComponent } from '@home/components/ai/solution/pane/solution-overview.component'; import { SolutionDashboardsComponent } from '@home/components/ai/solution/pane/solution-dashboards.component'; import { SolutionInstalledComponent } from '@home/components/ai/solution/pane/solution-installed.component'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; import { AiModule } from '@home/components/ai/ai.module'; @NgModule({ @@ -23,6 +24,7 @@ import { AiModule } from '@home/components/ai/ai.module'; SolutionOverviewComponent, SolutionDashboardsComponent, SolutionInstalledComponent, + SolutionJsonComponent, SolutionInfoDialogComponent, IssuesPopoverComponent ], diff --git a/ui-ngx/src/app/modules/home/home.component.scss b/ui-ngx/src/app/modules/home/home.component.scss index 9be747f736..1d857a7284 100644 --- a/ui-ngx/src/app/modules/home/home.component.scss +++ b/ui-ngx/src/app/modules/home/home.component.scss @@ -179,7 +179,7 @@ .tb-site-content { position: relative; - overflow-x: hidden; + overflow: hidden; } .tb-site-main.openAiAssistant { 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 0859394445..39695ee8ba 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -11754,6 +11754,9 @@ "view-as-user": "View as {{name}}", "json-note": "Edits here are applied as they are; the AI does not review them.", "json-tip": "View as JSON", + "download": "Download", + "download-file": "Download {{name}}", + "view-json": "View", "keys": "{ count, plural, =1 {1 key} other {# keys} }", "list": "List", "list-or-schema": "List or schema", @@ -11798,6 +11801,12 @@ "view-solution": "Solution", "view-as": "View as" }, + "view-as-name": "View as {{name}}", + "connect-devices": "Connect real devices", + "uninstalled-at": "Uninstalled at {{time}}.", + "uninstalled-note": "The entities are removed; the design is kept. Create solution installs it again.", + "installed-already": "Installed already.", + "installed-already-note": "The installed solution stays as it is until you create it again; creating then replaces it.", "what-should-it-do": "What should the solution do?", "what-it-becomes": "A description becomes profiles, roles, calculated fields, alarm rules and dashboards, on simulated devices.", "example-tip": "Puts the example in the composer", diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 0c300e90c8..8ebe327098 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -1316,6 +1316,30 @@ body.tb-ai-resizing, body.tb-ai-resizing * { user-select: none; } +.k-hint { + display: flex; + gap: 8px; + align-items: flex-start; + font-size: 14px; + line-height: 20px; + color: var(--tb-text-secondary, rgba(0, 0, 0, 0.6)); + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-54); + } + + b { + font-weight: 500; + color: var(--tb-ink-76); + } +} + .k-start { display: flex; align-items: center; From db58069a7782eb7325ba9dbf1b8e2f2bd6978e4c Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 6 Nov 2026 17:30:04 +0200 Subject: [PATCH 018/183] feat: the solution chat says what a solution is in a band over the hero's foot, shows a failed step or install in the chat instead of a toast, lists installed items that need a look, opens the pane when a step's result arrives or waits, shades the pane's head and foot over scrolled content, and marks a solution running in the chats list --- .../app/core/services/ai-solutions.service.ts | 22 ++ .../ai/solution/solution-chat.component.html | 48 +++- .../ai/solution/solution-chat.component.scss | 225 ++++++++++++++++++ .../ai/solution/solution-chat.component.ts | 95 +++++++- .../ai-assistant/ai-assistant.component.html | 2 + .../assets/locale/locale.constant-en_US.json | 13 + 6 files changed, 400 insertions(+), 5 deletions(-) diff --git a/ui-ngx/src/app/core/services/ai-solutions.service.ts b/ui-ngx/src/app/core/services/ai-solutions.service.ts index 1c7a5a5bf8..a85ad83d0f 100644 --- a/ui-ngx/src/app/core/services/ai-solutions.service.ts +++ b/ui-ngx/src/app/core/services/ai-solutions.service.ts @@ -17,6 +17,9 @@ export class AiSolutionsService { private _loaded = signal(false); readonly loaded = this._loaded.asReadonly(); + private _running = signal>(new Set()); + readonly running = this._running.asReadonly(); + private api = inject(SolutionsCreatorService); private dialog = inject(DialogService); private translate = inject(TranslateService); @@ -33,6 +36,25 @@ export class AiSolutionsService { ); } + setRunning(solutionId: string | undefined, running: boolean): void { + if (!solutionId || this._running().has(solutionId) === running) { + return; + } + this._running.update(set => { + const next = new Set(set); + if (running) { + next.add(solutionId); + } else { + next.delete(solutionId); + } + return next; + }); + } + + isRunning(solutionId: string): boolean { + return this._running().has(solutionId); + } + find(solutionId: string | undefined): SolutionInfo | undefined { return solutionId ? this._solutions().find(solution => solution.id === solutionId) : undefined; } diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html index 24f0d124eb..0c49096e0c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -53,7 +53,30 @@ }

{{ 'solution-creator.limits' | translate }}

+ +
+
+
+
+ {{ 'solution-creator.about-title' | translate }} + +
+
+ @for (feature of aboutFeatures; track feature.icon) { +
+ +
{{ feature.title | translate }}{{ feature.line | translate }}
+
+ } +
+
} @else if (creatorStep()) { @@ -119,6 +142,26 @@ {{ 'solution-creator.installed-already-note' | translate }}
} + @if (creatorStep() === 'result' && issues().length) { +
+

{{ 'solution-creator.issues-lead' | translate: {count: issues().length} }}

+
    + @for (issue of issues().slice(0, 6); track $index) { +
  • {{ issue.name }} · {{ (issue.status === 'ERROR' ? 'solution-creator.pane.status-error' : 'solution-creator.pane.status-warn') | translate }}
  • + } +
+
+ + {{ 'solution-creator.issues-tip-lead' | translate }} {{ 'solution-creator.issues-tip' | translate }} +
+
+ } + @if (failure(); as message) { +
+ + {{ message }} +
+ } @if (work(); as current) { } @@ -152,7 +195,8 @@
@if (showPane() && paneOpen()) { -
} @else { -
+
- } -
- @if (way() === 'terminal') { -
- } @else { -
-
- -
- } -
-

{{ (way() === 'terminal' ? 'ai-assistant.cli.note-terminal' : 'ai-assistant.cli.note-agent') | translate }}

- + + {{ 'ai-assistant.cli.hero.docs' | translate }} + +
+
@@ -66,7 +52,8 @@
  • @for (agent of agents; track agent.id) { - } @@ -77,8 +64,13 @@
  • diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss index 943424e131..9b8ce8b762 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss @@ -175,6 +175,7 @@ $hero-bg: #1b252c; margin: 0; font-size: 16px; line-height: 24px; + max-width: 56ch; letter-spacing: 0.15px; color: #b4bec6; text-wrap: pretty; @@ -223,50 +224,57 @@ $hero-bg: #1b252c; } .ai-cli-hero-set { - position: relative; display: grid; - justify-items: start; - gap: 12px; + gap: 24px; max-width: 680px; margin: 20px auto 0; } -.ai-cli-seg { - display: inline-flex; - padding: 2px; - border-radius: 100px; - background: rgba(255, 255, 255, 0.08); +.ai-cli-acts { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 20px; + padding-left: 72px; +} - button { - height: 30px; - padding: 0 14px; - border: 0; - border-radius: 100px; - background: none; - color: #b4bec6; - font-family: inherit; - font-size: var(--chat-line); - line-height: 1; - cursor: pointer; - transition: background-color $motion $ease, color $motion $ease; +.ai-cli-start { + display: inline-flex; + align-items: center; + gap: 6px; + height: 40px; + padding: 0 14px 0 18px; + border: 0; + border-radius: 10px; + background: var(--ai-dark-accent); + color: var(--ai-on-dark-accent); + font-family: inherit; + font-size: var(--chat-text); + font-weight: 500; + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: background-color $motion $ease; - b { - font-weight: 500; - } + .mat-icon { + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); + color: inherit; + transition: transform $motion $ease; + } - &:hover { - color: #fff; - } + &:hover { + background: var(--ai-dark-accent-hover); - &[aria-pressed="true"] { - background: var(--ai-dark-accent); - color: var(--ai-on-dark-accent); + .mat-icon { + transform: translateY(2px); } + } - &:focus-visible { - outline: 2px solid var(--ai-dark-accent-pale); - outline-offset: 2px; - } + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; } } @@ -274,21 +282,6 @@ $hero-bg: #1b252c; display: contents; } -.ai-cli-clamp { - position: relative; - justify-self: stretch; - min-width: 0; - display: grid; - - > .ai-cli-more-t { - position: absolute; - left: 50%; - bottom: 10px; - transform: translateX(-50%); - height: 28px; - } -} - .ai-cli-alt { display: inline-flex; align-items: center; @@ -312,6 +305,15 @@ $hero-bg: #1b252c; height: 18px; } + &, &:hover, &:focus { + border-bottom: 0; + text-decoration: none; + } + + &:is(a) { + letter-spacing: inherit; + } + &:hover { color: var(--ai-dark-accent-pale); } @@ -327,24 +329,6 @@ $hero-bg: #1b252c; } } -.ai-cli-foot { - justify-self: stretch; - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 4px 16px; - min-width: 0; -} - -.ai-cli-prompt-note { - margin: 0; - font-size: 13px; - line-height: 19px; - color: #9fadb7; - text-wrap: balance; -} - .ai-cli { max-width: 680px; margin: 24px auto 0; @@ -354,10 +338,14 @@ $hero-bg: #1b252c; text-wrap: pretty; } - :is(h2, p, .ai-cli-body > b, .ai-cli-step-head > b, .ai-cli-subs > li > b) { + :is(h2, p, .ai-cli-body > b, .ai-cli-step-head > b, .ai-cli-subs > li > b), .ai-cli-flow > li > :is(b, p) { text-wrap: balance; } + p { + letter-spacing: inherit; + } + code { padding: 1px 5px; border-radius: 4px; @@ -426,7 +414,7 @@ $hero-bg: #1b252c; } .ai-cli-pic { - height: 136px; + height: 120px; box-sizing: border-box; min-width: 0; padding: 0 16px; @@ -452,7 +440,7 @@ $hero-bg: #1b252c; border: 0; border-radius: 18px; background: var(--tb-surface); - box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.06), 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 20px rgba(16, 24, 40, 0.1); + box-shadow: 0 1px 3px color-mix(in srgb, var(--glow) 16%, transparent), 0 12px 26px -8px color-mix(in srgb, var(--glow) 46%, transparent); animation: ai-cli-rise $breathe ease-in-out infinite alternate; & + .ai-cli-logo { @@ -477,15 +465,49 @@ $hero-bg: #1b252c; font-family: var(--tb-mono); font-size: 12.5px; font-weight: 500; - line-height: 22px; + line-height: 20px; color: var(--tb-ink); + .commit { + display: flex; + align-items: center; + gap: 6px; + height: 20px; + min-width: 0; + margin-bottom: 6px; + font-size: var(--chat-meta); + font-weight: 400; + white-space: nowrap; + color: var(--tb-ink-54); + + .mat-icon { + flex: none; + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + color: var(--ai-selected); + } + + b { + flex: none; + font-weight: 500; + color: var(--ai-selected); + } + + > span:last-child { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + } + .row { position: relative; display: flex; align-items: center; gap: 6px; - height: 22px; + height: 20px; min-width: 0; padding-left: calc(var(--d) * 18px); white-space: nowrap; @@ -511,35 +533,53 @@ $hero-bg: #1b252c; &.tone-view { color: var(--entity-view-fg); } + + &.tone-rule { + color: var(--entity-rule-fg); + } } - &:not(:first-child)::before { + &:not(.top)::before { content: ''; position: absolute; left: calc((var(--d) - 1) * 18px + 7px); - top: -4px; - width: 8px; - height: 15px; - box-sizing: border-box; - border-left: 1px solid var(--k-stroke-hover); - border-bottom: 1px solid var(--k-stroke-hover); - border-bottom-left-radius: 5px; + top: 10px; + width: 9px; + border-top: 1px solid var(--k-stroke-hover); } - &:not(:first-child):not(.last)::after { + &:not(.top):not(.last)::after { content: ''; position: absolute; left: calc((var(--d) - 1) * 18px + 7px); - top: 6px; - bottom: -4px; + top: 0; + bottom: 0; border-left: 1px solid var(--k-stroke-hover); } + + &.last:not(.top)::before { + top: 0; + height: 11px; + box-sizing: border-box; + border-top: 0; + border-left: 1px solid var(--k-stroke-hover); + border-bottom: 1px solid var(--k-stroke-hover); + border-bottom-left-radius: 5px; + } + + &.first:not(.last)::after, &.first.last::before { + top: -1px; + } + + &.first.last::before { + height: 12px; + } } } .ai-cli-ask { display: grid; - gap: 4px; + gap: 2px; min-width: 0; font-family: var(--tb-mono); font-size: 12.5px; @@ -547,15 +587,29 @@ $hero-bg: #1b252c; line-height: 18px; color: var(--tb-ink-76); - .q { + .chk { + display: grid; + grid-template-columns: 12px minmax(0, 1fr); + gap: 4px; margin-bottom: 4px; + font-weight: 400; + color: var(--tb-ink-54); + + > i { + font-style: normal; + color: var(--ai-selected); + } + } + + .q { + margin-bottom: 2px; font-weight: 600; color: var(--tb-ink); } .opt { display: grid; - grid-template-columns: 12px minmax(0, 1fr); + grid-template-columns: 12px minmax(0, 1fr) auto; gap: 4px; margin: 0 -6px; padding: 2px 6px; @@ -567,6 +621,11 @@ $hero-bg: #1b252c; animation: ai-cli-lit $breathe ease-in-out infinite alternate; } + .enter { + color: var(--ai-selected); + opacity: 0.7; + } + &.on { background: var(--ai-selected-wash); color: var(--ai-selected-text); @@ -622,7 +681,7 @@ $hero-bg: #1b252c; z-index: 1; width: 44px; height: 44px; - border-radius: 50%; + border-radius: 13px; display: inline-flex; align-items: center; justify-content: center; @@ -792,7 +851,6 @@ $hero-bg: #1b252c; .ai-cli-keys { height: 36px; - margin-top: 6px; border-color: var(--k-stroke); color: var(--tb-ink-76); @@ -965,72 +1023,350 @@ $hero-bg: #1b252c; margin-top: 10px; } - .ai-cli-cta { - .tb-codeblock { - justify-self: stretch; - min-width: 0; - margin: 0; - border-radius: 8px; - box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1); + .ai-cli-term { + --term-bg: color-mix(in srgb, #{$hero-bg} 58%, #000); + --term-fg: var(--tb-code-fg); + --term-text: #9fadb7; + --term-muted: #7d8c96; + --term-faint: #5f6f7a; + --term-hover: #b4bec6; + --term-rule: rgba(255, 255, 255, 0.07); + --term-art: linear-gradient(90deg in oklab, var(--ai-dark-accent), var(--ai-light-lilac), var(--ai-light-peach)); + min-width: 0; + + .banner { + display: grid; + color: var(--term-muted); + + .art { + justify-self: start; + max-width: 100%; + margin-bottom: 10px; + overflow: hidden; + white-space: pre; + font-size: 12px; + line-height: 13px; + color: var(--ai-dark-accent-soft); + } - .tb-code { - white-space: pre-wrap; + b { + font-weight: 500; + color: var(--term-fg); + } + + i { + font-style: normal; + color: var(--ai-dark-accent); } } - .tb-codeblock-head { - color: var(--ai-dark-accent); - border-bottom-color: color-mix(in srgb, var(--ai-dark-accent) 16%, transparent); + .r { + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + min-width: 0; + overflow-wrap: anywhere; - > .tb-codeblock-label { + > i { + font-style: normal; color: var(--ai-dark-accent); - font-weight: 500; } - .tb-codecopy.labelled { + &.past { + opacity: 0.5; + } + + &.think { + color: var(--term-muted); + + > i { + display: inline-block; + transform: scale(1.5); + transform-origin: 30% 55%; + } + + &.done > i { + color: var(--term-faint); + } + } + + &.out.run .t { + color: var(--term-faint); + } + + &:is(.you, .tool, .say, .think) { + margin-top: var(--chat-line-lh); + } + + &.you { + color: #fff; + } + + &:is(.tool, .say, .ask) { + color: var(--term-fg); + } + + &.tool b { + font-weight: 500; color: var(--ai-dark-accent); - font: 500 12.5px/1 var(--tb-font); - - .mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - color: currentColor; - opacity: 1; + } + + &:is(.out, .ok, .ask) { + padding-left: 2ch; + } + + &.out > i { + color: var(--term-faint); + } + + &.say > i { + color: #fff; + } + } + + .caret { + display: inline-block; + width: 1ch; + height: 1.15em; + vertical-align: text-bottom; + background: var(--ai-dark-accent); + animation: ai-cli-lit $breathe ease-in-out infinite alternate; + + &.typing { + animation: none; + } + } + } + + @supports ((background-clip: text) or (-webkit-background-clip: text)) { + .ai-cli-term .banner .art { + background: var(--term-art); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + } + + @media (forced-colors: active) { + .ai-cli-term .banner .art { + background: none; + color: CanvasText; + } + } + + .ai-cli-term-bar { + display: flex; + align-items: flex-end; + min-width: 0; + + .dots { + flex: none; + display: flex; + gap: 6px; + margin: 0 4px 12px 14px; + + i { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.1); + } + } + + .tabs { + display: flex; + gap: 2px; + min-width: 0; + padding: 0 18px 0 10px; + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + } + + [role="tab"] { + position: relative; + flex: none; + height: 32px; + padding: 0 14px; + border: 0; + border-radius: 8px 8px 0 0; + background: none; + color: var(--term-muted); + font-family: var(--tb-mono); + font-size: var(--chat-meta); + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: color $motion $ease; + + &:hover { + background: rgba(255, 255, 255, 0.04); + color: var(--term-hover); + } + + &[aria-selected="true"] { + background: var(--term-bg); + color: var(--term-fg); + + &::before, &::after { + content: ''; + position: absolute; + bottom: 0; + width: 8px; + height: 8px; + pointer-events: none; } - &:hover { - background: color-mix(in srgb, var(--ai-dark-accent) 12%, transparent); - color: var(--ai-dark-accent-hover); + &::before { + left: -8px; + background: radial-gradient(circle at 0 0, transparent 8px, var(--term-bg) 8.5px); } - &.done { - background: color-mix(in srgb, var(--ai-dark-accent) 16%, transparent); - color: var(--ai-dark-accent-pale); + &::after { + right: -8px; + background: radial-gradient(circle at 100% 0, transparent 8px, var(--term-bg) 8.5px); } } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: -2px; + } } } - .ai-cli-clamp { - > .tb-codeblock { - min-width: 0; + .ai-cli-term-body { + height: 268px; + display: flex; + flex-direction: column; + border-radius: 10px; + background: var(--term-bg); + box-shadow: 0 18px 40px -18px rgba(0, 0, 0, 0.55); + overflow: hidden; + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; + } + } + + .ai-cli-term-view { + flex: 1; + min-height: 0; + box-sizing: border-box; + padding: 12px 16px 10px; + display: flex; + flex-direction: column; + overflow: hidden; + + &.full { + justify-content: flex-end; + -webkit-mask-image: linear-gradient(transparent, #000 30px); + mask-image: linear-gradient(transparent, #000 30px); + } + } + + .ai-cli-term-rows { + display: grid; + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--term-text); + transition: opacity .24s cubic-bezier(.05, .7, .1, 1); + + > .r:first-child { + margin-top: 0; + } + + &.out { + opacity: 0; + transition: opacity .16s cubic-bezier(.3, 0, .8, .15); + } + } + + .ai-cli-term-input { + flex: none; + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + padding: 10px 16px 12px; + box-shadow: inset 0 1px 0 var(--term-rule); + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: #fff; + overflow-wrap: anywhere; + + > i { + font-style: normal; + color: var(--ai-dark-accent); } - .tb-code { - padding-bottom: 48px; + &.menu .t { + display: grid; } - &.shut .tb-code { - $fade: linear-gradient(#000 calc(100% - 132px), rgba(0, 0, 0, 0.82) calc(100% - 108px), rgba(0, 0, 0, 0.5) calc(100% - 82px), - rgba(0, 0, 0, 0.2) calc(100% - 58px), rgba(0, 0, 0, 0.05) calc(100% - 40px), transparent calc(100% - 26px)); - max-height: 204px; + .opt { + color: var(--term-muted); + + &.on { + color: var(--ai-dark-accent); + } + + &.press { + color: var(--ai-dark-accent-pale); + } + } + } + + @container (min-width: 640px) { + .ai-cli-term { + width: 100%; + max-width: 600px; + margin-left: 72px; box-sizing: border-box; - overflow: hidden; - -webkit-mask-image: $fade; - mask-image: $fade; } } + + @container (max-width: 639px) { + .ai-cli-term-bar { + .dots { + display: none; + } + + .tabs { + padding: 0 10px; + } + } + + .ai-cli-term .banner .art { + font-size: 9.5px; + line-height: 10px; + } + } + + @media (prefers-reduced-motion: reduce) { + .ai-cli-term .caret, .ai-cli-term-rows { + animation: none; + transition: none; + } + } +} + +@container (max-width: 480px) { + .ai-cli-start .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +@media (max-width: 720px) { + .ai-cli-head .ob-title { + font-size: 22px; + line-height: 28px; + } } @media (prefers-reduced-motion: reduce) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts index 6d512f0a4e..87d3bac663 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts @@ -9,7 +9,7 @@ import { ElementRef, inject, Injector, - input, + NgZone, output, signal } from '@angular/core'; @@ -39,17 +39,18 @@ import { CliOs, CliWay } from '@home/components/ai/ai-cli.models'; +import { cliTerm, CliTerm } from '@home/components/ai/ai-cli-term'; interface CliPicks { way?: CliWay; build?: CliBuild; - open?: boolean; } interface CliTreeRow { depth: number; name: string; last: boolean; + first: boolean; icon: string; tone?: string; } @@ -69,8 +70,6 @@ export class AiCliGuideComponent { private static readonly PICKS_KEY = 'tb-ai-cli'; - copiedUntil = input(0); - closed = output(); readonly docs = CLI_DOCS; @@ -88,11 +87,10 @@ export class AiCliGuideComponent { readonly url = window.location.origin; readonly tree: CliTreeRow[] = [ - {depth: 0, name: 'thingsboard-project', last: true, icon: 'folder'}, - {depth: 1, name: 'solutions/office', last: true, icon: 'folder'}, - {depth: 2, name: 'devices', last: false, icon: 'memory', tone: 'device'}, - {depth: 2, name: 'dashboards', last: false, icon: 'dashboard', tone: 'view'}, - {depth: 2, name: 'device-profiles', last: true, icon: 'category', tone: 'device'} + {depth: 0, name: 'smart-retail', last: true, first: false, icon: 'folder'}, + {depth: 1, name: 'devices', last: false, first: true, icon: 'memory', tone: 'device'}, + {depth: 1, name: 'dashboards', last: false, first: false, icon: 'dashboard', tone: 'view'}, + {depth: 1, name: 'alarm-rules', last: true, first: false, icon: 'rule', tone: 'rule'} ]; private readonly picks = AiCliGuideComponent.readPicks(); @@ -101,8 +99,6 @@ export class AiCliGuideComponent { build = signal(CLI_BUILDS.some(item => item.id === this.picks.build) ? this.picks.build : 'sensor'); - promptOpen = signal(!!this.picks.open); - os = signal(AiCliGuideComponent.storedOs()); fullscreen = signal(false); @@ -114,12 +110,17 @@ export class AiCliGuideComponent { private router = inject(Router); private injector = inject(Injector); private host = inject>(ElementRef); + private zone = inject(NgZone); + private term: CliTerm | null = null; readonly hostElement = this.host.nativeElement; constructor() { const stop = onCodeTabGroup(CLI_OS_GROUP, id => this.os.set(id === 'windows' ? 'windows' : 'unix')); - inject(DestroyRef).onDestroy(stop); + inject(DestroyRef).onDestroy(() => { + stop(); + this.term?.destroy(); + }); afterRenderEffect(() => { this.way(); this.build(); @@ -150,22 +151,6 @@ export class AiCliGuideComponent { this.savePicks(); } - togglePrompt(event: Event): void { - const control = event.currentTarget as HTMLElement; - const top = control.getBoundingClientRect().top; - const open = !this.promptOpen(); - this.promptOpen.set(open); - this.savePicks(); - if (!open) { - afterNextRender(() => { - const scroller = this.scroller(); - if (scroller) { - scroller.scrollTop += control.getBoundingClientRect().top - top; - } - }, {injector: this.injector}); - } - } - toSteps(): void { const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; this.hostElement.querySelector('#ai-cli-steps')?.scrollIntoView({behavior: reduce ? 'auto' : 'smooth', block: 'start'}); @@ -194,7 +179,7 @@ export class AiCliGuideComponent { private fillSlots(): void { this.hostElement.querySelectorAll('.ai-cli-slot').forEach(slot => { - const key = slot.dataset.kind + ':' + (slot.dataset.key ?? '') + (slot.dataset.kind === 'prompt-hero' ? ':' + this.copiedUntil() : ''); + const key = slot.dataset.kind + ':' + (slot.dataset.key ?? ''); if (slot.dataset.built !== key) { slot.dataset.built = key; slot.replaceChildren(this.blockFor(slot.dataset.kind, slot.dataset.key)); @@ -206,13 +191,10 @@ export class AiCliGuideComponent { const copy = (text: string) => this.clipboard.copyFromContent(text); const say = (word: string) => this.translate.instant('ai-assistant.cli.' + word); switch (kind) { - case 'install-hero': - return this.installBlock(true); + case 'term': + return this.termBlock(); case 'install': - return this.installBlock(false); - case 'prompt-hero': - return labelledCodeBlock(say('setup-prompt'), say('setup-prompt-label'), 'text', this.translate, copy, - {labelledCopy: true, classes: 'wrap', copiedFor: Math.max(0, this.copiedUntil() - Date.now())}); + return this.installBlock(); case 'prompt': return labelledCodeBlock(say('setup-prompt'), say('setup-prompt-label'), 'text', this.translate, copy, {check: true, classes: 'wrap'}); @@ -234,14 +216,19 @@ export class AiCliGuideComponent { } } - private installBlock(hero: boolean): HTMLElement { + private termBlock(): HTMLElement { + this.term?.destroy(); + this.term = this.zone.runOutsideAngular(() => cliTerm((key, params) => this.translate.instant(key, params))); + return this.term.element; + } + + private installBlock(): HTMLElement { return codeTabsBlock([ {id: 'unix', label: this.translate.instant('ai-assistant.cli.mac-linux'), text: CLI_INSTALL.unix, lang: 'shell'}, {id: 'windows', label: this.translate.instant('ai-assistant.cli.windows'), text: CLI_INSTALL.windows, lang: 'powershell'} ], 'shell', this.translate, text => this.clipboard.copyFromContent(text), this.os() === 'windows' ? 1 : 0, tab => this.os.set(tab.id === 'windows' ? 'windows' : 'unix'), - {group: CLI_OS_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, - labelledCopy: hero, check: !hero}); + {group: CLI_OS_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, check: true}); } private agentBlock(text: (agent: CliAgentInfo) => string): HTMLElement { @@ -251,7 +238,7 @@ export class AiCliGuideComponent { } private savePicks(): void { - const picks: CliPicks = {way: this.way(), build: this.build(), open: this.promptOpen()}; + const picks: CliPicks = {way: this.way(), build: this.build()}; try { localStorage.setItem(AiCliGuideComponent.PICKS_KEY, JSON.stringify(picks)); } catch { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts new file mode 100644 index 0000000000..b38085e1c9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + CLI_ART, + CLI_TERM_HOLD, + CLI_TERM_SESSIONS, + CLI_TERM_WAIT, + CLI_VERSION, + CliTermRow, + CliTermSession +} from '@home/components/ai/ai-cli.models'; + +export interface CliTerm { + element: HTMLElement; + destroy: () => void; +} + +const MARK: Record = {you: '❯', tool: '●', out: '└', say: '●', ok: '✔', ask: '', think: '⠿'}; +const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'; + +let shownTab = 0; +let turning = true; +let termCount = 0; + +type Kid = Node | string | null; + +function el(tag: string, cls?: string, ...kids: Kid[]): HTMLElement { + const node = document.createElement(tag); + if (cls) { + node.className = cls; + } + kids.forEach(kid => { + if (kid != null) { + node.append(kid); + } + }); + return node; +} + +const jitter = (lo: number, hi: number) => lo + Math.random() * (hi - lo); + +export function cliTerm(say: (key: string, params?: Record) => string): CliTerm { + const calm = matchMedia('(prefers-reduced-motion: reduce)').matches; + const uid = 'ai-cli-term-' + (++termCount); + const t = (key: string) => say('ai-assistant.cli.term.' + key); + const list = el('div', 'ai-cli-term-rows'); + list.setAttribute('role', 'img'); + const view = el('div', 'ai-cli-term-view', list); + const typed = document.createTextNode(''); + const caret = el('span', 'caret'); + const line = el('span', 't', typed, caret); + const input = el('div', 'ai-cli-term-input', el('i', null, '❯'), line); + input.setAttribute('aria-hidden', 'true'); + const body = el('div', 'ai-cli-term-body', view, input); + body.setAttribute('role', 'tabpanel'); + body.id = uid + '-panel'; + body.tabIndex = 0; + const touch = () => { + turning = false; + }; + const pickTab = (k: number) => { + touch(); + if (k !== shownTab) { + play(k); + } + }; + const tabs = CLI_TERM_SESSIONS.map((session, k) => { + const tab = el('button', null, session.tab) as HTMLButtonElement; + tab.type = 'button'; + tab.setAttribute('role', 'tab'); + tab.id = `${uid}-tab-${k}`; + tab.setAttribute('aria-controls', body.id); + tab.addEventListener('click', () => pickTab(k)); + return tab; + }); + const strip = el('div', 'tabs', ...tabs); + strip.setAttribute('role', 'tablist'); + strip.setAttribute('aria-label', t('label')); + strip.addEventListener('keydown', (event: KeyboardEvent) => { + const k = tabs.indexOf(document.activeElement as HTMLButtonElement); + const n = tabs.length; + const to = ({ArrowRight: k + 1, ArrowLeft: k - 1 + n, Home: 0, End: n - 1} as Record)[event.key]; + if (k < 0 || to == null) { + return; + } + event.preventDefault(); + pickTab(to % n); + tabs[to % n].focus(); + }); + const dots = el('span', 'dots', el('i'), el('i'), el('i')); + dots.setAttribute('aria-hidden', 'true'); + const root = el('div', 'ai-cli-term', el('div', 'ai-cli-term-bar', dots, strip), body); + root.addEventListener('click', touch); + + let run = 0; + let spin: ReturnType | null = null; + let thinking: HTMLElement | null = null; + let t0 = 0; + let seen = true; + let hover = false; + let started = false; + let told = false; + let io: IntersectionObserver | null = null; + let fallback: ReturnType | null = null; + const timers = new Set>(); + + const later = (ms: number, fn: () => void) => { + const r = run; + const id = setTimeout(() => { + timers.delete(id); + if (r === run && root.isConnected) { + fn(); + } + }, ms); + timers.add(id); + }; + const stopSpin = () => { + if (spin) { + clearInterval(spin); + spin = null; + } + }; + const setInput = (text: string) => { + typed.data = text; + line.replaceChildren(typed, caret); + input.classList.remove('menu'); + caret.classList.toggle('typing', !!text); + }; + const stop = () => { + run += 1; + timers.forEach(clearTimeout); + timers.clear(); + stopSpin(); + thinking = null; + setInput(''); + }; + const fit = () => { + const room = view.clientHeight; + if (room) { + view.classList.toggle('full', list.offsetHeight > room - 16); + } + }; + const row = (kind: string, ...kids: Kid[]) => { + const r = el('span', 'r ' + kind, el('i', null, MARK[kind.split(' ')[0]]), el('span', 't', ...kids)); + list.insertBefore(r, thinking); + fit(); + return r; + }; + const toolRow = (item: CliTermRow) => row('tool', el('b', null, item.tool), `(${item.arg})`); + const think = () => { + t0 = Date.now(); + thinking = el('span', 'r think', el('i', null, SPIN[0]), el('span', 't', t('thinking'))); + list.append(thinking); + fit(); + let f = 0; + const glyph = thinking.firstChild as HTMLElement; + spin = setInterval(() => { + if (!root.isConnected) { + stopSpin(); + return; + } + f += 1; + glyph.textContent = SPIN[f % SPIN.length]; + }, 90); + }; + const done = () => { + if (!thinking) { + return; + } + stopSpin(); + thinking.classList.add('done'); + thinking.firstChild.textContent = '⠿'; + thinking.lastChild.textContent = say('ai-assistant.cli.term.done', {seconds: Math.max(1, Math.round((Date.now() - t0) / 1000))}); + thinking = null; + }; + const send = (text: string, next: () => void) => { + setInput(''); + row('you', text); + think(); + later(jitter(900, 1500), next); + }; + const type = (text: string, next: () => void) => { + let n = 0; + const tick = () => { + n += 1; + typed.data = text.slice(0, n); + caret.classList.add('typing'); + const ch = text[n - 1]; + if (n < text.length) { + later(ch === ' ' ? jitter(45, 120) : /[.,:]/.test(ch) ? jitter(140, 280) : jitter(30, 75), tick); + } else { + later(420, () => send(text, next)); + } + }; + tick(); + }; + const pick = (options: string[], next: () => void) => { + input.classList.add('menu'); + line.replaceChildren(...options.map((option, j) => el('span', 'opt' + (j ? '' : ' on'), `${j + 1}. ${option}`))); + later(1400, () => { + (line.firstChild as HTMLElement).classList.add('press'); + later(240, () => send(options[0], next)); + }); + }; + const stream = (node: HTMLElement, text: string, next: () => void) => { + const words = text.split(' '); + let n = 0; + const tick = () => { + n = Math.min(words.length, n + 1 + Math.floor(Math.random() * 3)); + node.textContent = words.slice(0, n).join(' '); + fit(); + if (n < words.length) { + later(jitter(45, 100), tick); + } else { + next(); + } + }; + tick(); + }; + const step = (rows: CliTermRow[], i: number) => { + if (i >= rows.length) { + done(); + if (turning) { + later(CLI_TERM_HOLD, advance); + } + return; + } + const item = rows[i]; + const go = () => later(CLI_TERM_WAIT[(rows[i + 1] ?? {kind: 'you'}).kind], () => step(rows, i + 1)); + if (item.kind === 'you') { + done(); + type(t(item.text), () => step(rows, i + 1)); + return; + } + if (item.kind === 'pick') { + done(); + pick(item.options.map(t), () => step(rows, i + 1)); + return; + } + if (item.kind === 'tool') { + toolRow(item); + go(); + return; + } + if (item.kind === 'out') { + const r = row('out run', t('running')); + later(item.ms || 1200, () => { + r.classList.remove('run'); + r.lastChild.textContent = t(item.text); + fit(); + go(); + }); + return; + } + stream(row(item.kind).lastChild as HTMLElement, t(item.text), go); + }; + const advance = () => { + if (!turning) { + return; + } + if (hover || !seen || document.hidden) { + later(600, advance); + return; + } + play((shownTab + 1) % CLI_TERM_SESSIONS.length); + }; + const intro = (session: CliTermSession) => { + if (session.banner) { + list.append(el('div', 'banner', el('span', 'art', CLI_ART), el('b', null, CLI_VERSION), + el('span', null, el('i', null, '✔'), ' ' + t('connected')), el('span', null, el('i', null, '✔'), ' ' + t('detected')))); + fit(); + return; + } + (session.intro ?? []).forEach(item => { + const r = item.kind === 'done' ? row('think done', say('ai-assistant.cli.term.done', {seconds: item.seconds})) + : item.kind === 'tool' ? toolRow(item) : row(item.kind, t(item.text)); + r.classList.add('past'); + }); + }; + const still = (rows: CliTermRow[]) => rows.forEach(item => { + if (item.kind === 'tool') { + toolRow(item); + } else if (item.kind === 'pick') { + row('you', t(item.options[0])); + } else { + row(item.kind, t(item.text)); + } + }); + const mark = (k: number) => { + shownTab = k; + tabs.forEach((tab, j) => { + tab.setAttribute('aria-selected', String(j === k)); + tab.tabIndex = j === k ? 0 : -1; + }); + if (strip.scrollWidth > strip.clientWidth) { + strip.scrollLeft += tabs[k].getBoundingClientRect().left - strip.getBoundingClientRect().left - 10; + } + body.setAttribute('aria-labelledby', tabs[k].id); + list.setAttribute('aria-label', say('ai-assistant.cli.term.picture', {about: t(CLI_TERM_SESSIONS[k].tab + '.about')})); + }; + const opening = (k: number) => { + list.replaceChildren(); + view.classList.remove('full'); + intro(CLI_TERM_SESSIONS[k]); + if (calm) { + still(CLI_TERM_SESSIONS[k].rows); + } + }; + const begin = (k: number) => later(CLI_TERM_WAIT.you, () => step(CLI_TERM_SESSIONS[k].rows, 0)); + function play(k: number): void { + stop(); + mark(k); + started = true; + const go = () => { + list.classList.remove('out'); + opening(k); + if (!calm) { + begin(k); + } + }; + if (list.firstChild && !calm) { + list.classList.add('out'); + later(260, go); + } else { + go(); + } + } + const refit = () => { + if (root.isConnected) { + fit(); + } + }; + + shownTab = Math.min(shownTab, CLI_TERM_SESSIONS.length - 1); + mark(shownTab); + opening(shownTab); + requestAnimationFrame(refit); + const destroy = () => { + stop(); + io?.disconnect(); + if (fallback) { + clearTimeout(fallback); + } + }; + if (calm) { + return {element: root, destroy}; + } + root.addEventListener('pointerenter', (event: PointerEvent) => { + if (event.pointerType === 'mouse') { + hover = true; + } + }); + root.addEventListener('pointerleave', () => { + hover = false; + }); + const start = () => { + if (!started) { + started = true; + begin(shownTab); + } + }; + if ('IntersectionObserver' in window) { + io = new IntersectionObserver(entries => { + told = true; + seen = entries[entries.length - 1].isIntersecting; + if (seen) { + start(); + } + }, {threshold: 0.2}); + io.observe(root); + } + fallback = setTimeout(() => { + fallback = null; + if (!told && root.isConnected) { + seen = true; + start(); + } + }, 1500); + return {element: root, destroy}; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts index 46dfc24860..b8651dcee3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts @@ -13,8 +13,6 @@ export const CLI_OS_GROUP = 'cli-os'; export const CLI_AGENT_GROUP = 'cli-agent'; -export const CLI_COPIED_MS = 4000; - export const CLI_DOCS = 'https://thingsboard.io/docs/cli/'; export const CLI_INSTALL: Record = { @@ -28,11 +26,12 @@ export interface CliAgentInfo { run: string; restart: string; get: string; + glow: string; } export const CLI_AGENTS: CliAgentInfo[] = [ - {id: 'claude', name: 'Claude Code', run: 'claude', restart: 'claude --continue', get: 'https://claude.com/claude-code'}, - {id: 'antigravity', name: 'Antigravity', run: 'agy', restart: 'agy', get: 'https://antigravity.google/'} + {id: 'claude', name: 'Claude Code', run: 'claude', restart: 'claude --continue', get: 'https://claude.com/claude-code', glow: '#D97757'}, + {id: 'antigravity', name: 'Antigravity', run: 'agy', restart: 'agy', get: 'https://antigravity.google/', glow: '#3186FF'} ]; export interface CliBuildInfo { @@ -72,6 +71,108 @@ export const CLI_DOCS_LINKS: CliDocsLink[] = [ {key: 'all', icon: 'menu_book', path: ''} ]; +export type CliTermKind = 'you' | 'pick' | 'tool' | 'out' | 'say' | 'ok' | 'ask' | 'done'; + +export interface CliTermRow { + kind: CliTermKind; + text?: string; + tool?: string; + arg?: string; + ms?: number; + options?: string[]; + seconds?: number; +} + +export interface CliTermSession { + tab: string; + banner?: boolean; + intro?: CliTermRow[]; + rows: CliTermRow[]; +} + +export const CLI_VERSION = 'thingsboard-cli 4.4.0.2.post1'; + +export const CLI_ART = [ + ' _____ _ _ ____ _ ', + '|_ _| |__ (_)_ __ __ _ ___| __ ) ___ __ _ _ __ __| |', + ' | | | \'_ \\| | \'_ \\ / _` / __| _ \\ / _ \\ / _` | \'__/ _` |', + ' | | | | | | | | | | (_| \\__ \\ |_) | (_) | (_| | | | (_| |', + ' |_| |_| |_|_|_| |_|\\__, |___/____/ \\___/ \\__,_|_| \\__,_|', + ' |___/ ' +].join('\n'); + +export const CLI_TERM_WAIT: Record = {you: 1200, pick: 300, tool: 380, out: 60, say: 520, ok: 110, ask: 260}; + +export const CLI_TERM_HOLD = 6000; + +export const CLI_TERM_SESSIONS: CliTermSession[] = [ + { + tab: 'office-sensor', + banner: true, + rows: [ + {kind: 'you', text: 'office-sensor.you'}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'office-sensor.written', ms: 2600}, + {kind: 'say', text: 'office-sensor.ready'}, + {kind: 'ok', text: 'office-sensor.device'}, + {kind: 'ok', text: 'office-sensor.alarm'}, + {kind: 'ok', text: 'office-sensor.dashboard'}, + {kind: 'ask', text: 'office-sensor.ask'}, + {kind: 'pick', options: ['office-sensor.stream', 'office-sensor.deploy-only', 'office-sensor.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push office'}, + {kind: 'out', text: 'office-sensor.deployed', ms: 1500}, + {kind: 'tool', tool: 'Bash', arg: 'tb emulator run --duration 5m'}, + {kind: 'out', text: 'office-sensor.streaming', ms: 1100} + ] + }, + { + tab: 'smart-retail', + intro: [ + {kind: 'tool', tool: 'Bash', arg: 'tb device list'}, + {kind: 'out', text: 'smart-retail.devices'}, + {kind: 'say', text: 'smart-retail.connected'}, + {kind: 'done', seconds: 6} + ], + rows: [ + {kind: 'you', text: 'smart-retail.you'}, + {kind: 'tool', tool: 'Skill', arg: 'design-solution-architecture'}, + {kind: 'out', text: 'smart-retail.designed', ms: 2800}, + {kind: 'say', text: 'smart-retail.approve'}, + {kind: 'pick', options: ['smart-retail.step', 'smart-retail.whole']}, + {kind: 'say', text: 'smart-retail.first'}, + {kind: 'ok', text: 'smart-retail.overview'}, + {kind: 'ok', text: 'smart-retail.store'}, + {kind: 'ask', text: 'smart-retail.build'}, + {kind: 'pick', options: ['smart-retail.yes', 'smart-retail.not-yet']}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built', ms: 3000}, + {kind: 'say', text: 'smart-retail.next'} + ] + }, + { + tab: 'freezer-limits', + intro: [ + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built'}, + {kind: 'say', text: 'smart-retail.next'}, + {kind: 'done', seconds: 41} + ], + rows: [ + {kind: 'you', text: 'freezer-limits.you'}, + {kind: 'tool', tool: 'Skill', arg: 'update-solution'}, + {kind: 'out', text: 'freezer-limits.updated', ms: 2400}, + {kind: 'say', text: 'freezer-limits.done'}, + {kind: 'ok', text: 'freezer-limits.attribute'}, + {kind: 'ok', text: 'freezer-limits.alarm'}, + {kind: 'ok', text: 'freezer-limits.dashboard'}, + {kind: 'ask', text: 'freezer-limits.ask'}, + {kind: 'pick', options: ['freezer-limits.push', 'freezer-limits.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push smart-retail --profile dev'}, + {kind: 'out', text: 'freezer-limits.deployed', ms: 1600} + ] + } +]; + export function cliOs(): CliOs { const nav = navigator as Navigator & {userAgentData?: {platform?: string}}; return /win/i.test(nav.userAgentData?.platform || navigator.platform || '') ? 'windows' : 'unix'; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts index 22c1fc5a49..334fc0dc83 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -157,7 +157,6 @@ export interface CodeBlockOptions { icon?: boolean; check?: boolean; labelledCopy?: boolean; - copiedFor?: number; classes?: string; } @@ -409,17 +408,13 @@ function copyBtn(text: string | (() => string), translate: TranslateService, cop done(LABELLED_COPIED_MS); } }); - if (options.copiedFor > 0) { - done(options.copiedFor); - } return button; } - if (options.check) { - button.append(icon('check', 'tb-mat-16 tb-copy-ok')); - } + button.append(icon('check', 'tb-mat-16 tb-copy-ok')); button.addEventListener('click', () => { if (copy(typeof text === 'function' ? text() : text)) { button.classList.add('copied'); + announceCopied(translate.instant('ai-assistant.copied')); clearTimeout(timer); timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); } @@ -427,6 +422,20 @@ function copyBtn(text: string | (() => string), translate: TranslateService, cop return button; } +let copiedRegion: HTMLElement | null = null; + +export function announceCopied(words: string): void { + if (!copiedRegion?.isConnected) { + copiedRegion = element('div', 'tb-ai-sr-only'); + copiedRegion.setAttribute('role', 'status'); + copiedRegion.setAttribute('aria-live', 'polite'); + document.body.append(copiedRegion); + } + const region = copiedRegion; + region.textContent = ''; + setTimeout(() => region.textContent = words, 30); +} + function icon(name: string, size: string): HTMLElement { const glyph = element('span', `mat-icon material-icons notranslate ${size}`); glyph.setAttribute('aria-hidden', 'true'); @@ -790,4 +799,12 @@ export function decorateTables(root: HTMLElement): void { root.querySelectorAll('table td, table th').forEach((cell: HTMLElement) => { cell.classList.toggle('long', (cell.textContent ?? '').trim().length > LONG_CELL); }); + root.querySelectorAll('table td:first-child').forEach((cell: HTMLElement) => { + if (cell.firstElementChild?.classList.contains('k-md-lead') && cell.childNodes.length === 1) { + return; + } + const lead = element('span', 'k-md-lead'); + lead.append(...Array.from(cell.childNodes)); + cell.append(lead); + }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html new file mode 100644 index 0000000000..4a09dc26d5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -0,0 +1,116 @@ + +
    + @if (folded()) { + + } @else { +
    + {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} + @if (arrived()) { + + } +
    +
    + @if (handOver().text) { + + } + @if (handOver().choice; as choice) { +
    +
    + + {{ choice.question }} + + @for (option of choice.options; track option.id) { + + } + +
    + @if (choiceText()) { +
    + } +
    + } + @if (handOver().steps.length) { +
      + @for (step of handOver().steps; track $index; let i = $index) { +
    1. + + @if (step.values.length || step.markdown) { +
      + @for (value of step.values; track $index; let v = $index) { +
      + + {{ value.label }} + {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} + @if (value.secret) { + + } + +
      + } + @if (step.markdown) { + + } +
      + } +
    2. + } +
    + } + @if (quiet() || stoppedQuiet()) { +
    +
    + + {{ 'ai-assistant.hand-over.nothing-heard' | translate: {minutes: quietMinutes()} }} + @if (waiting()) { + {{ clock() }} + } +
    +
    + + +
    +
    + } @else if (waiting()) { +
    + + {{ waitLabel() }} + {{ clock() }} +
    + } +
    + } +
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts new file mode 100644 index 0000000000..d76d19b58a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { Clipboard } from '@angular/cdk/clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; +import { announceCopied, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; + +export interface AiHandOverWait { + running: boolean; + startedAt: number; + progress?: string; + check?: AiConnectionCheck | null; +} + +const MIN_SILENCE_MS = 120000; +const COPIED_MS = 1500; + +@Component({ + selector: 'tb-ai-hand-over', + templateUrl: './ai-hand-over.component.html', + standalone: false +}) +export class AiHandOverComponent { + + handOver = input.required(); + wait = input(null); + time = input(0); + + @Output() prompt = new EventEmitter(); + + private host = inject(ElementRef); + private translate = inject(TranslateService); + private clipboard = inject(Clipboard); + + readonly picked = signal(null); + readonly ticked = signal>(new Set()); + readonly shown = signal>(new Set()); + readonly copied = signal(null); + readonly now = signal(Date.now()); + readonly open = signal(false); + + readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null); + readonly choiceText = computed(() => this.handOver().choice?.options.find(option => option.id === this.choiceValue())?.text ?? ''); + + readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); + readonly folded = computed(() => this.arrived() && !this.open()); + + readonly waiting = computed(() => !!this.wait()?.running); + readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); + readonly clock = computed(() => { + const seconds = Math.floor(this.elapsed() / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; + }); + readonly silenceMs = computed(() => Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0))); + readonly quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs()); + readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000))); + readonly stoppedQuiet = computed(() => { + const wait = this.wait(); + return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; + }); + + constructor() { + const timer = setInterval(() => { + if (this.waiting()) { + this.now.set(Date.now()); + } + }, 1000); + inject(DestroyRef).onDestroy(() => clearInterval(timer)); + effect(() => { + this.choiceText(); + this.handOver(); + this.folded(); + setTimeout(() => decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copy(text))); + }); + } + + waitLabel(): string { + return this.translate.instant('ai-assistant.hand-over.wait-' + (this.handOver().waitFor ?? 'message')); + } + + pick(id: string): void { + this.picked.set(id); + } + + tick(index: number): void { + const next = new Set(this.ticked()); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + this.ticked.set(next); + } + + done(index: number): boolean { + return this.ticked().has(index) !== (this.handOver().steps[index]?.done === true); + } + + reveal(key: string): void { + const next = new Set(this.shown()); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + this.shown.set(next); + } + + masked(value: string): string { + return value.length > 8 ? value.slice(0, 4) + '••••••••' + value.slice(-4) : '••••••••'; + } + + copy(key: string, value: string): void { + if (this.clipboard.copy(value)) { + this.copied.set(key); + announceCopied(this.translate.instant('ai-assistant.copied')); + setTimeout(() => this.copied.set(null), COPIED_MS); + } + } + + say(key: string): void { + this.prompt.emit(this.translate.instant(key)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html new file mode 100644 index 0000000000..86ade52c20 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -0,0 +1,47 @@ + +@let current = view(); + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts new file mode 100644 index 0000000000..c025bea6fc --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { NotificationService } from '@core/http/notification.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AddonType, SubscriptionEntry, subscriptionEntryToEntityType } from '@shared/models/subscription.models'; +import { AiPlatformLimit } from '@shared/models/ai-chat.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +type LimitAction = 'request' | 'license' | 'pricing' | 'none'; + +interface LimitView { + icon: string; + title: string; + text: string; + action: LimitAction; + usage: boolean; + requestLabel?: string; + storageKey: string; + send?: () => Observable; +} + +const PRICING_URL = 'https://thingsboard.io/pricing/'; +const WL_REQUESTED_STORAGE_KEY = 'wlRequested'; +const PE_PACK_REQUESTED_STORAGE_KEY = 'pePackRequested'; +const FEATURE_KEYS: Record = { + [SubscriptionEntry.WHITE_LABELING]: 'white-labeling', + INTEGRATIONS: 'integrations', + SCHEDULER: 'scheduler', + REPORTING: 'reporting' +}; + +@Component({ + selector: 'tb-ai-limit-out', + templateUrl: './ai-limit-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiLimitOutComponent { + + platformLimit = input.required(); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private translate = inject(TranslateService); + private readonly store = inject(Store); + private readonly user = getCurrentAuthUser(this.store); + private readonly authState = getCurrentAuthState(this.store); + + readonly pricingUrl = PRICING_URL; + readonly state = signal('idle'); + readonly view = computed(() => this.viewOf(this.platformLimit())); + + constructor() { + effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle')); + } + + request(): void { + const send = this.view().send; + if (!send || this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + send().subscribe({ + next: () => { + this.rememberRequested(this.view().storageKey); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + private viewOf(limit: AiPlatformLimit): LimitView { + const tenantAdmin = this.user?.authority === Authority.TENANT_ADMIN; + const sysAdmin = this.user?.authority === Authority.SYS_ADMIN; + const customer = this.user?.authority === Authority.CUSTOMER_USER; + const oldLicense = !(this.authState?.licenseVersion > 1); + const config = {ignoreLoading: true, ignoreErrors: true}; + if (limit.errorCode === 41 && limit.entityType) { + const entityType = limit.entityType; + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(entityType)}), + text: customer + ? this.say('tenant-text-plain', {entities: this.entities(entityType).toLowerCase()}) + : this.say('tenant-text', {limit: limit.limit, entities: this.entities(entityType).toLowerCase()}), + action: 'request', + usage: tenantAdmin, + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${entityType}:${limit.limit}`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(entityType, false, config) + }; + } + const entry = limit.subscriptionEntry as SubscriptionEntry; + const licensedType = subscriptionEntryToEntityType.get(entry); + if (limit.subscriptionErrorCode === 'LIMIT_REACHED' && licensedType) { + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(licensedType)}), + text: oldLicense + ? this.say('license-text-old', {entities: this.entities(licensedType).toLowerCase()}) + : this.say('license-text', {entities: this.entities(licensedType).toLowerCase()}), + action: oldLicense ? 'pricing' : (sysAdmin ? 'license' : 'request'), + usage: false, + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${licensedType}:license`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(licensedType, true, config) + }; + } + const featureKey = FEATURE_KEYS[limit.subscriptionEntry ?? '']; + if (limit.subscriptionErrorCode === 'FEATURE_DISABLED' && featureKey) { + const whiteLabeling = entry === SubscriptionEntry.WHITE_LABELING; + const grant = !!this.authState?.communityGrantLicense; + const addon = whiteLabeling && !grant ? AddonType.WHITE_LABELING : AddonType.PROFESSIONAL_UPGRADE; + return { + icon: whiteLabeling ? 'palette' : 'lock', + title: grant + ? this.translate.instant(`platform-feature.${featureKey}.not-in-ce-grant`) + : (whiteLabeling ? this.translate.instant('platform-feature.white-labeling.not-in-plan') + : this.say('feature-title', {feature: this.say(`feature.${featureKey}`)})), + text: this.say(addon === AddonType.WHITE_LABELING ? 'white-labeling-text' : 'pack-text'), + action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'), + usage: false, + requestLabel: 'subscription.request-access', + storageKey: addon === AddonType.WHITE_LABELING ? WL_REQUESTED_STORAGE_KEY : PE_PACK_REQUESTED_STORAGE_KEY, + send: () => this.notificationService.sendAddonAccessRequest(addon, config) + }; + } + return { + icon: 'lock', + title: this.say('license-required'), + text: limit.message ?? '', + action: sysAdmin ? 'license' : 'none', + usage: false, + storageKey: '' + }; + } + + private entities(entityType: EntityType): string { + const translations = entityTypeTranslations.get(entityType); + return translations ? this.translate.instant(translations.typePlural) as string : entityType; + } + + private say(key: string, params?: object): string { + return this.translate.instant('ai-assistant.limit-out.' + key, params); + } + + private wasRequested(key: string): boolean { + if (!key) { + return false; + } + try { + const stored = localStorage.getItem(key); + return stored === 'sent' || stored === 'true'; + } catch { + return false; + } + } + + private rememberRequested(key: string): void { + if (!key) { + return; + } + try { + localStorage.setItem(key, key === WL_REQUESTED_STORAGE_KEY || key === PE_PACK_REQUESTED_STORAGE_KEY ? JSON.stringify(true) : 'sent'); + } catch { + return; + } + } +} 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 78f6ee88fd..bde8d07d8e 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 @@ -689,15 +689,17 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; justify-content: center; box-sizing: border-box; - min-width: 22px; - height: 22px; - padding: 0 6px; + min-width: 20px; + height: 20px; + padding: 0 5px; border: 1px solid var(--tb-line); border-bottom-width: 2px; - border-radius: 6px; - background: var(--tb-surface); - color: var(--tb-ink-54); - font: 500 12px/1 var(--tb-font); + border-radius: 5px; + background: none; + color: var(--k-faint); + font: 400 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; pointer-events: none; transform: translateY(-50%); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts index 99815a7b25..328ffb0945 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -43,7 +43,7 @@ export function aiWidgetThumb(): string { template: ` @let rec = view();
    + [class.with-pic]="picture()" [class.primary]="!!primaryAction()" [class.open-icon]="primaryAction() === 'open'" [class.tight]="tight()" [class.with-details]="hasFoot()">
    @if (picture()) {
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts index 328ffb0945..3424bc45fc 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -48,9 +48,11 @@ export function aiWidgetThumb(): string { @if (picture()) { + } @else if (fact.chip; as chip) { + + @if (chip.image) { + + } @else if (chip.icon) { + + } + {{ factValue(fact) }} + } @else if (factLink(fact); as url) { {{ factValue(fact) }} } @else if (fact.secret && !revealed().has(view().hood?.key + $index)) { @@ -122,6 +131,9 @@
    } @case ('code') { + @if (block.title) { +
    {{ ('ai-assistant.action.' + block.title) | translate }}
    + }
    {{ block.text }}
    } @case ('links') { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts index a3a980e031..79ed424ae8 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts @@ -161,7 +161,7 @@ export class AiActionDetailComponent { if (fact.entity) { return this.nameOf(fact.entity) ?? fact.entity.id ?? '—'; } - return fact.value?.startsWith('ai-assistant.') ? this.translate.instant(fact.value) : fact.value ?? ''; + return fact.value && (fact.chip || fact.value.startsWith('ai-assistant.')) ? this.translate.instant(fact.value) : fact.value ?? ''; } factLink(fact: AiDetailFact): string | null { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts index dadb0040e3..c44c0e5b3b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -2,6 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 import { AiAction } from '@shared/models/ai-chat.models'; import { SCADA_SYMBOL_PART_WORDS, WIDGET_PART_WORDS, widgetParts } from '@home/components/ai/ai-action.models'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; const WIDGET_PART_LANGS: Record = {html: 'html', css: 'css', js: 'javascript'}; @@ -61,6 +63,7 @@ export interface AiDetailFact { mono?: boolean; secret?: boolean; images?: {current?: string; value?: string}; + chip?: {icon?: string; image?: string}; } export interface AiDetailCommand { @@ -86,7 +89,7 @@ export type AiDetailBlock = | {type: 'commands'; rows: AiDetailCommand[]} | {type: 'links'; rows: AiDetailLink[]} | {type: 'markdown'; text: string} - | {type: 'code'; label: string; text: string; lang?: string} + | {type: 'code'; label: string; text: string; lang?: string; title?: string} | {type: 'note'; text: AiDetailText} | {type: 'text'; text: string} | {type: 'json'; label: string; text: string} @@ -250,12 +253,73 @@ function scadaSymbolOverviewBlocks(overview: Values): AiDetailBlock[] { ...(problems.length ? [{type: 'list' as const, label: text('scada-symbol-problems'), rows: problems.slice(0, MAX_ROWS)}] : [])]; } +const CODE_KEYS = new Set(['script', 'decoder', 'encoder', 'tbelDecoder', 'tbelEncoder', 'jsDecoder', 'jsEncoder']); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + +function converterTypeFact(type: unknown, label = K + 'fact.type'): AiDetailFact[] { + const key = converterTypeTranslationMap.get(type as ConverterType); + return key ? [{label, value: key, chip: {icon: CONVERTER_ICONS[type as string]}}] : []; +} + +function integrationTypeFact(type: unknown): AiDetailFact[] { + const info = integrationTypeInfoMap.get(type as IntegrationType); + return info ? [{label: K + 'fact.integration-type', value: info.name, chip: {image: info.icon}}] : []; +} + +function typedFact(key: string, value: unknown): AiDetailFact[] { + if (key === 'integrationType') { + return integrationTypeFact(value); + } + if (key === 'type' || key === 'converterType') { + return converterTypeFact(value); + } + return []; +} + +function codeBlocks(values: Values): AiDetailBlock[] { + return Object.entries(values).filter(([key, value]) => CODE_KEYS.has(key) && str(value)) + .map(([, value]) => ({type: 'code', title: 'script', label: 'TBEL', lang: 'tbel', text: (value as string).replace(/\n+$/, '')})); +} + +function messageBlock(label: string, value: unknown): AiDetailBlock[] { + if (isObject(value) || Array.isArray(value)) { + return [{type: 'json', label, text: JSON.stringify(value, null, 2)}]; + } + const text = str(value); + if (!text) { + return []; + } + const parsed = /^[[{]/.test(text) ? aiParse(text) : undefined; + return isObject(parsed) || Array.isArray(parsed) ? [{type: 'json', label, text: JSON.stringify(parsed, null, 2)}] : [{type: 'json', label, text}]; +} + +function converterBlocks(values: Values, result: unknown): AiDetailBlock[] { + const rows = [...converterTypeFact(values.type), ...integrationTypeFact(values.integrationType), + ...facts(values, ['type', 'integrationType', 'payload', 'metadata', 'integrationMetadata', ...CODE_KEYS])]; + const outcome = isObject(result) ? result : {}; + return [ + ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...codeBlocks(values), + ...messageBlock('payload', values.payload), + ...messageBlock('metadata', values.metadata), + ...messageBlock('error', outcome.error), + ...messageBlock('output', outcome.output), + ...messageBlock('result', outcome.result) + ]; +} + function facts(values: Values, skip: string[] = [], names?: AiDetailNames): AiDetailFact[] { const rows: AiDetailFact[] = []; for (const [key, value] of Object.entries(values)) { if (skip.includes(key) || value === null || value === undefined || value === '') { continue; } + const typed = typedFact(key, value); + if (typed.length) { + rows.push(...typed); + continue; + } if (names && /Id$/.test(key) && (typeof value === 'string' || isObject(value)) && idOf(value)) { const ref = entity(value, isObject(value) ? value.entityType : undefined, names); rows.push(ref.name ? {label: aiHumanize(key.replace(/Id$/, '')), raw: true, entity: ref} : {label: aiHumanize(key), raw: true, value: idOf(value), mono: true}); @@ -292,8 +356,8 @@ function json(label: string, value: unknown): AiDetailBlock[] { function generic(value: unknown, label: string, skip: string[] = [], names?: AiDetailNames): AiDetailBlock[] { if (typeof value === 'string') { - const trimmed = value.trim(); - return !trimmed || /^OK\.?$/i.test(trimmed) ? [] : [{type: 'text', text: trimmed.replace(/^OK:\s*/i, '')}]; + const trimmed = value.trim().replace(/^OK:\s*/i, ''); + return !trimmed || /^OK\.?$/i.test(trimmed) || UUID.test(trimmed) ? [] : [{type: 'text', text: trimmed}]; } if (isObject(value) && Object.keys(value).length <= 16 && flat(value)) { const rows = facts(value, skip, names); @@ -2018,10 +2082,14 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail return {hood: text('save-image', {name: str(saved.title) ?? str(values.title) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}, ...images([{value: saved.link}])] : generic(result, 'result')}; } + case 'test_converter': + return {blocks: converterBlocks(values, result)}; + case 'save_converter': + return {blocks: [...converterBlocks(values, undefined), ...generic(result, 'result', [], names)]}; case 'reprocess_calculated_field': return {hood: text('reprocess', {entity: of(values.calculatedFieldId, 'CALCULATED_FIELD'), from: dateText(values.startTime ?? values.startTs), to: endText(values.endTime ?? values.endTs)}), blocks: generic(result, 'result')}; } - const request = Object.keys(values).length ? (flat(values) ? [{type: 'facts', rows: facts(values, [], names)} as AiDetailBlock] : json('request', values)) : []; + const request = Object.keys(values).length ? (flat(values) ? [{type: 'facts', rows: facts(values, [...CODE_KEYS], names)} as AiDetailBlock, ...codeBlocks(values)] : json('request', values)) : []; return {blocks: [...request, ...generic(result, 'result', [], names)]}; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html index ac3c919e2b..1fd53e8632 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -19,6 +19,13 @@ {{ duration() }} }
    + @if (arrival()?.readings?.length) { +
    + @for (reading of arrival().readings; track reading.key) { + {{ reading.key }}{{ reading.value }} + } +
    + } @if (listing(); as hub) {
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss index f9ddbc8d1e..7143edb765 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -65,3 +65,31 @@ margin: 8px 0 4px; } } + +.k-arrived { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + margin: 4px 0 0 28px; + font-size: var(--chat-line, 14px); + line-height: 22px; + + .k-reading { + display: inline-flex; + align-items: baseline; + gap: 6px; + } + + code { + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + color: var(--tb-ink); + } + + b { + font: 600 13px/18px var(--tb-mono); + color: var(--tb-ink); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index 0669b0960e..b805eae38a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -12,6 +12,7 @@ import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-t import { aiActionDetailView, AiDetailFact, AiDetailNames, aiParse } from '@home/components/ai/ai-action-detail.models'; import { AiAction, + aiConnectionCheckOf, aiEntityKind, aiActionDuration, aiActionWords @@ -114,11 +115,32 @@ export class AiActionLineComponent { return this.autoApproved() ? this.translate.instant('ai-assistant.action.auto-approved', {words}) : words; }); + arrival = computed(() => { + const action = this.action(); + const values = aiParse(action.arguments) as {waitSeconds?: unknown} | null; + if (action.tool !== 'check_connection' || action.status !== 'SUCCESS' || !(Number(values?.waitSeconds) > 0)) { + return null; + } + const check = aiConnectionCheckOf(action.result); + if (!check?.dataArriving) { + return null; + } + const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + return { + text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys') + + (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}), + readings: check.readings + }; + }); + private outcomeWords(): string { const action = this.action(); if (this.outcomeText()) { return this.outcomeText(); } + if (this.arrival()) { + return this.arrival().text; + } if (action.status === 'FAILURE') { return this.reason(action.result) ?? this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index 466bc0dd75..bb6232e992 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -331,6 +331,7 @@ export interface AiHandOver { steps: AiHandOverStep[]; waitFor?: 'message' | 'uplink' | 'gateway'; intervalSeconds?: number; + quiet?: string; } const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; @@ -373,7 +374,7 @@ export function aiHandOverOf(args: unknown): AiHandOver | null { const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; const interval = Number(values.intervalSeconds); return {title, text: text(values.text), choice, steps, waitFor, - intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined}; + intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet)}; } export interface AiConnectionCheck { @@ -382,6 +383,7 @@ export interface AiConnectionCheck { name?: string; note?: string; readings: {key: string; value: string}[]; + keyCount: number; } export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { @@ -402,7 +404,7 @@ export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { add(values.telemetry); (Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), - note: text(values.note), readings: readings.slice(0, 6)}; + note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size}; } export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index 0e42a05666..f59b3e2b60 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -30,10 +30,16 @@
    @for (fact of facts; track $index) {
    @if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
    -
    @if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
    +
    @if (fact.chip; as chip) { @if (chip.image) { } @else if (chip.icon) { }{{ fact.value }} } @else if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
    }
    } + @for (block of codeBlocks; track $index) { + @if (block.current !== undefined) { +
    {{ block.current }}
    + } +
    {{ block.value }}
    + } @if (changes.length) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index aac545a1ae..82c5597d31 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { + AfterViewChecked, ChangeDetectorRef, Component, ElementRef, @@ -13,6 +14,10 @@ import { ViewChild } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; +import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; import { AiApprovalReview, AiReviewField, @@ -39,6 +44,9 @@ export interface AiReviewRow { value: string; image?: boolean; currentImage?: boolean; + code?: boolean; + lang?: string; + chip?: {icon?: string; image?: string}; } const MAX_FIELDS = 5; @@ -63,6 +71,79 @@ const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrad const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol']); +const BLOCK_FIELDS = new Set(['script']); + +const DETAILED_TOOLS = new Set(['save_converter']); + +const JSON_BLOCK_AT = 80; + +function prettyJson(value: string | undefined | null): string | null { + const trimmed = value?.trim() ?? ''; + if (trimmed.length < JSON_BLOCK_AT || !/^[[{]/.test(trimmed)) { + return null; + } + try { + const parsed = JSON.parse(trimmed); + return parsed && typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : null; + } catch { + return null; + } +} + +const DIFF_CONTEXT = 2; + +function withoutTs(text: string): string { + try { + const parsed = JSON.parse(text); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'ts' in parsed) { + const rest = {...parsed}; + delete rest.ts; + return JSON.stringify(rest, null, 2); + } + } catch { + } + return text; +} + +function lineDiff(before: string, after: string): string { + const a = before.split('\n'); + const b = after.split('\n'); + const table: number[][] = Array.from({length: a.length + 1}, () => new Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]); + } + } + const rows: {mark: ' ' | '-' | '+'; text: string}[] = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + rows.push({mark: ' ', text: a[i++]}); + j++; + } else if (i < a.length && (j >= b.length || table[i + 1][j] >= table[i][j + 1])) { + rows.push({mark: '-', text: a[i++]}); + } else { + rows.push({mark: '+', text: b[j++]}); + } + } + const keep = rows.map((row, index) => row.mark !== ' ' + || rows.slice(Math.max(0, index - DIFF_CONTEXT), index + DIFF_CONTEXT + 1).some(near => near.mark !== ' ')); + const out: string[] = []; + rows.forEach((row, index) => { + if (keep[index]) { + out.push(row.mark + ' ' + row.text); + } else if (keep[index - 1] || index === 0) { + out.push(' …'); + } + }); + return out.join('\n'); +} + +const isBlock = (field: AiReviewField): boolean => BLOCK_FIELDS.has(field.id) || !!prettyJson(field.value) || !!prettyJson(field.current); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/; const STACK_AT = 24; @@ -76,7 +157,7 @@ const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASS styleUrls: ['./ai-approval-card.component.scss'], standalone: false }) -export class AiApprovalCardComponent implements OnChanges { +export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { @Input() data: ToolExecutionRequested; @@ -106,6 +187,8 @@ export class AiApprovalCardComponent implements OnChanges { private readonly cd = inject(ChangeDetectorRef); private readonly translate = inject(TranslateService); + private readonly clipboard = inject(ClipboardService); + private readonly host = inject(ElementRef); private readonly loader = inject(AiRecordLoaderService); @@ -113,6 +196,10 @@ export class AiApprovalCardComponent implements OnChanges { private listingId: string | null = null; + ngAfterViewChecked(): void { + decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copyFromContent(text)); + } + ngOnChanges(changes: SimpleChanges): void { this.loadListing(); if ((this.data?.autoApproved || this.autoApprove) && this.state === 'pending' && !this.completedExecution) { @@ -142,7 +229,7 @@ export class AiApprovalCardComponent implements OnChanges { startedAt: this.data.time ?? Date.now(), affectedEntities: result.affectedEntities ?? [] }; - this.handedFacts = this.reviewFacts(); + this.handedFacts = DETAILED_TOOLS.has(this.data.tool ?? '') ? [] : this.reviewFacts(); } this.cd.detectChanges(); } @@ -227,7 +314,9 @@ export class AiApprovalCardComponent implements OnChanges { } const parts = [this.alarmRule ? this.translate.instant('ai-assistant.review.type.ALARM_RULE') : this.typeLabel(review.entityType)]; if (review.detail && !this.alarmRule) { - parts.push(DETAIL_TOKENS.has(review.detail) ? this.translate.instant('ai-assistant.review.detail.' + review.detail) : review.detail); + const integration = review.entityType === 'INTEGRATION' ? integrationTypeInfoMap.get(review.detail as IntegrationType) : undefined; + parts.push(DETAIL_TOKENS.has(review.detail) ? this.translate.instant('ai-assistant.review.detail.' + review.detail) + : integration ? this.translate.instant(integration.name) : review.detail); } if (review.target) { parts.push(this.translate.instant(PROFILE_TYPES.has(review.entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', @@ -237,18 +326,26 @@ export class AiApprovalCardComponent implements OnChanges { } get facts(): AiReviewRow[] { - const rows = [...this.rows('FACT').slice(0, MAX_FIELDS), ...this.rows('CHANGE', field => field.current === undefined || field.current === null)]; + const rows = [...this.rows('FACT', field => !isBlock(field)).slice(0, MAX_FIELDS), + ...this.rows('CHANGE', field => !isBlock(field) && (field.current === undefined || field.current === null))]; if (this.listing && this.review?.target) { rows.push({label: this.translate.instant('ai-assistant.record.set-up-on'), labelCode: false, valueCode: false, value: this.review.target}); } return rows; } + get codeBlocks(): AiReviewRow[] { + return [...this.rows('FACT', field => isBlock(field)), + ...this.rows('CHANGE', field => isBlock(field)).map(row => row.current === undefined ? row + : {...row, value: row.lang === 'json' ? lineDiff(withoutTs(row.current), withoutTs(row.value)) : lineDiff(row.current, row.value), + current: undefined, lang: 'diff'})]; + } + private reviewFacts(): AiDetailFact[] { return [ - ...this.rows('FACT').map(row => row.image ? {label: row.label, raw: true, images: {value: row.value}} - : {label: row.label, raw: true, value: row.value, mono: row.valueCode}), - ...this.rows('CHANGE').map(row => row.image || row.currentImage + ...this.rows('FACT', field => !isBlock(field)).map(row => row.image ? {label: row.label, raw: true, images: {value: row.value}} + : {label: row.label, raw: true, value: row.value, mono: row.valueCode, chip: row.chip}), + ...this.rows('CHANGE', field => !isBlock(field)).map(row => row.image || row.currentImage ? {label: row.label, raw: true, images: {current: row.currentImage ? row.current : undefined, value: row.image ? row.value : undefined}} : {label: row.label, raw: true, value: `${row.current ?? '—'} → ${row.value}`, mono: row.valueCode}) ]; @@ -260,7 +357,7 @@ export class AiApprovalCardComponent implements OnChanges { } get changes(): AiReviewRow[] { - return this.rows('CHANGE', field => field.current !== undefined && field.current !== null); + return this.rows('CHANGE', field => !isBlock(field) && field.current !== undefined && field.current !== null); } get unchanged(): AiReviewRow[] { @@ -319,13 +416,28 @@ export class AiApprovalCardComponent implements OnChanges { label: field.name ?? this.translate.instant('ai-assistant.review.field.' + field.id), labelCode: !!field.name, valueCode: CODE_FIELDS.has(field.id) && field.value !== undefined && field.value !== null, - current: kind === 'CHANGE' ? this.value(field, field.current) : undefined, - value: this.value(field, field.value), + current: kind !== 'CHANGE' || (isBlock(field) && (field.current === undefined || field.current === null)) ? undefined + : prettyJson(field.current) ?? this.value(field, field.current), + value: prettyJson(field.value) ?? this.value(field, field.value), image: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.value ?? ''), - currentImage: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.current ?? '') + currentImage: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.current ?? ''), + code: isBlock(field), + lang: BLOCK_FIELDS.has(field.id) ? 'tbel' : 'json', + chip: this.chip(field) })); } + private chip(field: AiReviewField): {icon?: string; image?: string} | undefined { + if (field.id === 'integrationType') { + const info = integrationTypeInfoMap.get(field.value as IntegrationType); + return info ? {image: info.icon} : undefined; + } + if (field.id === 'type' && converterTypeTranslationMap.has(field.value as ConverterType)) { + return {icon: CONVERTER_ICONS[field.value]}; + } + return undefined; + } + private value(field: AiReviewField, value: string | undefined): string { if (value === undefined || value === null) { return this.translate.instant('ai-assistant.review.not-set'); @@ -333,6 +445,12 @@ export class AiApprovalCardComponent implements OnChanges { if (field.id === 'when' && !isNaN(Date.parse(value))) { return new Date(value).toLocaleString(); } + if (field.id === 'integrationType' && integrationTypeInfoMap.has(value as IntegrationType)) { + return this.translate.instant(integrationTypeInfoMap.get(value as IntegrationType).name); + } + if (field.id === 'type' && converterTypeTranslationMap.has(value as ConverterType)) { + return this.translate.instant(converterTypeTranslationMap.get(value as ConverterType)); + } if (field.id && VALUE_TOKENS[field.id]?.includes(value)) { return this.translate.instant(`ai-assistant.review.value.${field.id}-${value}`); } 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 9883601024..289e1aafa0 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 @@ -85,7 +85,7 @@ } @else if (msg.from === 'ACTION' && handOvers[$index]; as card) {
    - +
    } @else if (msg.from === 'ACTION' && asking?.index === $index) {
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 3e0ead471d..4fcef0ad40 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -634,6 +634,24 @@ &::ng-deep tb-ai-action-detail { @include ai-code-blocks; } + + &::ng-deep tb-ai-hand-over { + @include ai-code-blocks; + } + + &::ng-deep tb-ai-approval-card { + @include ai-code-blocks; + + .k-review-code { + margin-top: 10px; + + .tb-code { + max-height: 320px; + overflow-y: auto; + scrollbar-width: thin; + } + } + } } .action-ways { 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 2d4443befa..fa86f5628a 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 @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { Component, ElementRef, EventEmitter, HostListener, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; -import { AiQuestion, AiQuestionAnswer, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { ActionChatMessage, AiQuestion, AiQuestionAnswer, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; import { ClipboardService } from 'ngx-clipboard'; import { TranslateService } from '@ngx-translate/core'; import { @@ -116,6 +116,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Output() changePlan = new EventEmitter(); @Output() openFile = new EventEmitter(); @Output() prompt = new EventEmitter(); + @Output() stopRun = new EventEmitter(); @Output() compose = new EventEmitter(); @Output() answer = new EventEmitter<{message: string; secrets?: Record}>(); @@ -816,9 +817,20 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { const cards: Record = {}; const waits = new Set(); let current = -1; + let early = -1; + const waitOf = (message: ActionChatMessage, index: number): AiHandOverWait => { + const running = message.data.status === 'RUNNING' && this.loading; + if (running) { + waits.add(index); + } + return {running, startedAt: message.data.startedAt, progress: message.data.progress, + endedAt: message.data.durationMs != null ? message.data.startedAt + message.data.durationMs : undefined, + check: running ? null : aiConnectionCheckOf(message.data.result)}; + }; this.messages.forEach((message, index) => { if (message.from === 'USER') { current = -1; + early = -1; return; } if (message.from !== 'ACTION') { @@ -829,14 +841,17 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { if (handOver) { cards[index] = {handOver, wait: null}; current = index; + if (early >= 0 && handOver.waitFor) { + cards[index].wait = waitOf(this.messages[early] as ActionChatMessage, early); + early = -1; + } } - } else if (message.data.tool === CHECK_CONNECTION_TOOL && current >= 0 && cards[current].handOver.waitFor + } else if (message.data.tool === CHECK_CONNECTION_TOOL && Number((message.data.arguments as {waitSeconds?: unknown})?.waitSeconds) > 0) { - const running = message.data.status === 'RUNNING' && this.loading; - cards[current].wait = {running, startedAt: message.data.startedAt, progress: message.data.progress, - check: running ? null : aiConnectionCheckOf(message.data.result)}; - if (running) { - waits.add(index); + if (current >= 0 && cards[current].handOver.waitFor) { + cards[current].wait = waitOf(message, index); + } else if (current < 0) { + early = index; } } }); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 6681acb69e..6022e31a11 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -91,6 +91,7 @@ [ghostFirst]="true" (openFile)="showFile($event)" (prompt)="ask($event)" + (stopRun)="stop()" (compose)="composeText($event)" (answer)="ask($event.message, $event.secrets)" (editMessage)="promptInput?.setValue($event)"> diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts index 334fc0dc83..245130e19a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -72,9 +72,52 @@ export function decorateCodeBlocks(root: HTMLElement, translate: TranslateServic }); } +export function aiFileFences(markdown: string): {text: string; files: string[]} { + const files: string[] = []; + let open: string | null = null; + const text = (markdown ?? '').split('\n').map(line => { + const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line); + if (!fence) { + return line; + } + if (open) { + if (fence[2].startsWith(open) && !fence[3].trim()) { + open = null; + } + return line; + } + open = fence[2]; + const info = fence[3].trim(); + const words = info.split(/\s+/); + const fileOf = (word: string) => /^[\w.-]+\.\w+$/.test(word ?? '') ? word : null; + const name = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); + files.push(name ?? ''); + if (!name) { + return line; + } + const lang = words.length > 1 ? words[0] : fileLanguage(name).lang; + return fence[1] + fence[2] + lang; + }).join('\n'); + return {text, files}; +} + +export function labelFileBlocks(root: HTMLElement, files: string[]): void { + root.querySelectorAll('pre > code').forEach((code, index) => { + const name = files[index]; + if (name && !code.hasAttribute('data-file')) { + code.setAttribute('data-file', name); + code.setAttribute('data-label', name); + } + }); +} + function languageOf(pre: HTMLElement): CodeLanguage | null { const classes = [pre.className, pre.querySelector('code')?.className ?? ''].join(' '); const name = /(?:^|\s)language-([\w+#-]+)/.exec(classes)?.[1]?.toLowerCase(); + const file = pre.querySelector('code')?.getAttribute('data-file'); + if (file && (!name || name === 'text' || name === 'plaintext' || name === 'none')) { + return {...fileLanguage(file), label: file}; + } if (!name || name === 'text' || name === 'plaintext' || name === 'none') { return null; } @@ -85,6 +128,8 @@ function languageOf(pre: HTMLElement): CodeLanguage | null { function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { const text = (pre.textContent ?? '').replace(/\n$/, ''); + const file = pre.querySelector('code')?.getAttribute('data-file'); + const noCopy = pre.querySelector('code')?.hasAttribute('data-nocopy'); const language = languageOf(pre); const lang = language?.lang ?? 'text'; const shell = lang === 'shell' || lang === 'powershell'; @@ -102,7 +147,7 @@ function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: st pre.className = 'tb-code'; pre.replaceChildren(code); const lineCount = text.split('\n').length; - const folds = lineCount > FOLD_LINES; + const folds = lineCount > FOLD_LINES && lang !== 'diff'; const block = element('div', 'tb-codeblock'); const wrapper = pre.closest('.code-wrapper'); if (wrapper) { @@ -136,11 +181,11 @@ function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: st head.append(icon(language.icon, 'tb-mat-16'), label); } const wrap = wrapBtn(block, text, translate); - head.append(...[wrap, copyButton].filter(Boolean)); + head.append(...[wrap, noCopy ? null : copyButton, file ? downloadBtn(file, text, translate) : null].filter(Boolean)); block.append(head, pre); } else { copyButton.classList.add('floating'); - block.append(pre, copyButton); + block.append(...[pre, noCopy ? null : copyButton].filter(Boolean)); } } @@ -436,6 +481,24 @@ export function announceCopied(words: string): void { setTimeout(() => region.textContent = words, 30); } +function downloadBtn(file: string, text: string, translate: TranslateService): HTMLButtonElement { + const button = element('button', 'tb-codecopy labelled tb-download') as HTMLButtonElement; + button.type = 'button'; + button.setAttribute('aria-label', translate.instant('ai-assistant.code.download-file', {name: file})); + const word = element('span', 'lbl'); + word.textContent = translate.instant('ai-assistant.code.download'); + button.append(icon('download', 'tb-mat-16'), word); + button.addEventListener('click', () => { + const url = URL.createObjectURL(new Blob([text.endsWith('\n') ? text : text + '\n'], {type: 'text/plain'})); + const link = document.createElement('a'); + link.href = url; + link.download = file; + link.click(); + setTimeout(() => URL.revokeObjectURL(url)); + }); + return button; +} + function icon(name: string, size: string): HTMLElement { const glyph = element('span', `mat-icon material-icons notranslate ${size}`); glyph.setAttribute('aria-hidden', 'true'); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html index 4a09dc26d5..1df2219ef4 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -4,25 +4,29 @@ SPDX-License-Identifier: BUSL-1.1 --> -
    +
    @if (folded()) { - +
    + {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} +
    + +

    {{ arrivedLine() }}

    } @else {
    - {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ 'ai-assistant.hand-over.needs-you' | translate }} {{ handOver().title }} - @if (arrived()) { - - }
    + @if (arrived()) { + + } @else if (time()) { + + }
    @if (handOver().text) { - + } @if (handOver().choice; as choice) {
    @@ -41,7 +45,7 @@
    @if (choiceText()) { -
    +
    }
    } @@ -59,26 +63,27 @@ @if (step.values.length || step.markdown) {
    @for (value of step.values; track $index; let v = $index) { -
    - - {{ value.label }} - {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} +
    + + {{ value.label }} + {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} @if (value.secret) { - } -
    } @if (step.markdown) { - + }
    } @@ -95,6 +100,9 @@ {{ clock() }} }
    + @if (handOver().quiet) { +

    {{ handOver().quiet }}

    + }
    } @else if (waiting()) {
    - + {{ waitLabel() }} {{ clock() }} + + +
    }
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index d76d19b58a..9fc8279671 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -4,12 +4,13 @@ import { Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inje import { Clipboard } from '@angular/cdk/clipboard'; import { TranslateService } from '@ngx-translate/core'; import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; -import { announceCopied, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; +import { aiFileFences, announceCopied, decorateCodeBlocks, labelFileBlocks } from '@home/components/ai/ai-code-block'; export interface AiHandOverWait { running: boolean; startedAt: number; progress?: string; + endedAt?: number; check?: AiConnectionCheck | null; } @@ -29,6 +30,8 @@ export class AiHandOverComponent { @Output() prompt = new EventEmitter(); + @Output() stop = new EventEmitter(); + private host = inject(ElementRef); private translate = inject(TranslateService); private clipboard = inject(Clipboard); @@ -45,6 +48,11 @@ export class AiHandOverComponent { readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); readonly folded = computed(() => this.arrived() && !this.open()); + readonly arrivedLine = computed(() => { + const wait = this.wait(); + const at = wait?.endedAt ? new Date(wait.endedAt).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : ''; + return this.translate.instant('ai-assistant.hand-over.arrived-' + (this.handOver().waitFor ?? 'message'), {time: at}); + }); readonly waiting = computed(() => !!this.wait()?.running); readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); @@ -71,10 +79,25 @@ export class AiHandOverComponent { this.choiceText(); this.handOver(); this.folded(); - setTimeout(() => decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copy(text))); + setTimeout(() => this.decorate()); }); } + md(text: string): string { + return aiFileFences(text).text; + } + + files(text: string): string { + return aiFileFences(text).files.join('|'); + } + + decorate(): void { + const root = this.host.nativeElement as HTMLElement; + root.querySelectorAll('tb-markdown[data-files]').forEach(markdown => + labelFileBlocks(markdown, (markdown.dataset.files ?? '').split('|'))); + decorateCodeBlocks(root, this.translate, text => this.clipboard.copy(text)); + } + waitLabel(): string { return this.translate.instant('ai-assistant.hand-over.wait-' + (this.handOver().waitFor ?? 'message')); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts index 91413bb29d..aff1efef08 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts @@ -214,7 +214,7 @@ export class AiQuestionComponent { } shown(item: {question: AiQuestion; answer: string}): string { - return item.question.secret && item.answer ? '••••••••' : item.answer; + return item.question.secret && item.answer && item.answer !== this.translate.instant('ai-assistant.question.no-answer') ? '••••••••' : item.answer; } next(): void { @@ -237,7 +237,9 @@ export class AiQuestionComponent { skipAll(): void { if (!this.disabled()) { - this.skip.emit(this.questions().map(question => ({question, answer: this.defaultOf(question)}))); + this.skip.emit(this.questions().map(question => this.given(question) + ? {question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length} + : {question, answer: this.defaultOf(question)})); } } @@ -253,6 +255,12 @@ export class AiQuestionComponent { } } + private given(question: AiQuestion): boolean { + return question.multiple && !this.isFree(question) + ? this.answerOf(question) !== this.translate.instant('ai-assistant.question.none') + : this.ready(question); + } + private answers(): AiQuestionAnswer[] { return this.questions().map(question => ({question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length})); } 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 7689787064..db2adc302b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -1144,6 +1144,7 @@ "yes": "Yes", "no": "No", "fact": { + "integration-type": "Integration type", "link": "Link", "subject": "Subject", "last-connect": "Last connected", @@ -2151,6 +2152,11 @@ "details": "Details", "request": "Request", "result": "Result", + "payload": "Payload", + "script": "Script", + "metadata": "Metadata", + "output": "Output", + "error": "Error", "template": "Template", "event": "Event", "account": "Account", @@ -2174,8 +2180,20 @@ "aria": "AI credits: {{used}} of {{max}} used this month" }, "hand-over": { + "stop-listening": "Stop listening", "needs-you": "Needs you", "fold": "Fold", + "unfold": "Show the steps", + "arrived-message": "The first message arrived at {{time}}.", + "arrived-message-from": "The first message from {{name}} arrived at {{time}}.", + "arrived-uplink": "The first uplink arrived at {{time}}.", + "arrived-uplink-from": "The first uplink from {{name}} arrived at {{time}}.", + "arrived-gateway": "The gateway connected at {{time}}.", + "arrived-gateway-from": "{{name}} connected at {{time}}.", + "arrived-keys": "The first message arrived at {{time}}, with {{count}} keys:", + "arrived-keys-from": "The first message from {{name}} arrived at {{time}}, with {{count}} keys:", + "arrived-key": "The first message arrived at {{time}}, with 1 key:", + "arrived-key-from": "The first message from {{name}} arrived at {{time}}, with 1 key:", "show": "Show", "hide": "Hide", "copied": "Copied", @@ -2438,7 +2456,9 @@ "lines": "{ count, plural, =1 {1 line} other {# lines} }", "wrap-lines": "Wrap lines", "one-line-each": "One line each", - "wrap-long-lines": "Wrap long lines" + "wrap-long-lines": "Wrap long lines", + "download": "Download", + "download-file": "Download {{name}}" }, "task": { "connect-device": { @@ -2493,6 +2513,7 @@ "ask-again": "Ask again", "ask-again-message": "Ask me again for the same change.", "field": { + "integrationType": "Integration type", "agent": "Agent", "install": "Install", "runs": "Runs", diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 87f2982ab8..eaaa920f0d 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -4955,13 +4955,64 @@ tb-ai-action-detail.k-detail { margin-top: 10px; max-height: 320px; overflow: auto; + box-sizing: border-box; + padding: 10px 14px; + border-radius: 10px; + background: color-mix(in srgb, var(--tb-ink) 3%, transparent); + box-shadow: inset 0 0 0 1px var(--tb-line); font-size: 13px; line-height: 20px; color: var(--tb-ink-76); overflow-wrap: anywhere; + scrollbar-width: thin; + scrollbar-color: var(--tb-ink-38) transparent; + + p, ul, ol, li, blockquote, table { + margin: 0 0 6px; + padding-left: 0; + padding-right: 0; + font-size: 13px; + line-height: 20px; + } + + ul, ol { + padding-left: 20px; + } + + li { + margin: 0 0 2px; + } + + h1, h2, h3, h4, h5, h6 { + margin: 12px 0 4px; + padding: 0; + font-size: 13px; + line-height: 20px; + font-weight: 600; + color: var(--tb-ink); + + &:first-child { + margin-top: 0; + } + } - p, ul, ol { + pre { margin: 0 0 6px; + padding: 8px 10px; + border-radius: 6px; + font-size: 12px; + line-height: 18px; + white-space: pre-wrap; + } + + hr { + margin: 8px 0; + border: 0; + border-top: 1px solid var(--tb-line); + } + + img { + display: none; } } @@ -6586,40 +6637,57 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { color: var(--tb-ink); > .k-head { - display: flex; + display: grid; + grid-template-columns: auto minmax(0, 1fr); + column-gap: 6px; + row-gap: 2px; align-items: center; - gap: 6px; - min-height: 24px; - font-size: var(--chat-head); - line-height: var(--chat-head-lh); + padding-right: 44px; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); font-weight: 500; white-space: nowrap; color: var(--tb-caution-text); > .mat-icon { - font-size: var(--chat-icon); - width: var(--chat-icon); - height: var(--chat-icon); - line-height: var(--chat-icon); + margin-top: 1px; + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; } .k-sub { - flex: 1; + grid-column: 1 / -1; min-width: 0; white-space: normal; - font-weight: 400; - color: var(--tb-ink-76); - } + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); - .k-hand-close { - flex: none; - margin: -6px -8px -6px 0; - color: var(--tb-ink-54); + &::first-letter { + text-transform: uppercase; + } } } + > .k-time { + position: absolute; + right: 16px; + top: 14px; + } + + > .k-hand-close { + position: absolute; + right: 6px; + top: 4px; + color: var(--tb-ink-54); + } + > .k-body { margin-top: 10px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + text-wrap: pretty; > * + * { margin-top: 12px; @@ -6627,62 +6695,101 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { p { margin: 0; + font-size: inherit; + line-height: inherit; + letter-spacing: inherit; } - .tb-markdown-view { - p { + .tb-markdown-view [class*="tb-markdown-view-"] { + > p, > div, > ul, > ol, > table, > h1, > h2, > h3, > h4, > h5, > h6 { + padding-left: 0; + padding-right: 0; + margin-left: 0; + } + + p, li { padding: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: .25px; + color: var(--tb-ink); } - p + p { + > * + * { margin-top: 8px; } + + ul, ol { + margin-bottom: 0; + padding-left: 22px; + } + + li + li { + margin-top: 4px; + } + + h1, h2, h3, h4, h5, h6 { + padding: 0; + margin-bottom: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + } + + strong, b { + font-weight: 500; + } + + code:not([class*=language-]):not(pre code) { + display: inline-block; + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + letter-spacing: 0; + color: var(--tb-ink); + vertical-align: baseline; + } } - > .k-wait:last-child, > .k-quiet:last-child { + > .k-wait:last-child, > .k-quiet:last-child, > .k-waitrow:last-child { margin: 14px calc(-1 * var(--chat-card-pad)) 0; padding: 12px var(--chat-card-pad) 0; border-top: 1px solid var(--k-stroke); } } - &.folded { - padding-top: 8px; - padding-bottom: 8px; + &.done { + padding: 10px 16px; + background: transparent; box-shadow: none; - } - .k-hand-fold { - display: flex; - align-items: center; - gap: 8px; - width: 100%; - padding: 0; - border: 0; - background: none; - font: inherit; - color: var(--tb-ink-76); - text-align: left; - cursor: pointer; - - > .mat-icon:first-child { - color: var(--ai-teal-500, var(--tb-primary-500)); - } + > .k-head { + color: var(--tb-text-secondary); - > span { - flex: 1; - min-width: 0; + .k-sub { + font-size: 14px; + line-height: 20px; + color: var(--tb-ink-76); + } } - .k-hand-fold-tg { - color: var(--tb-ink-54); + > .k-body { + margin-top: 4px; + color: var(--tb-text-secondary); } } .k-steps { list-style: none; - margin: 0; + margin-inline: 0; + margin-bottom: 0; padding: 0; + + &:first-child { + margin-top: 0; + } + display: grid; gap: 10px; @@ -6736,49 +6843,11 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { } .k-value { - display: flex; - align-items: center; - gap: 8px; min-width: 0; - padding: 2px 4px 2px 10px; - border: 1px solid var(--k-stroke); - border-radius: 8px; - background: color-mix(in srgb, var(--tb-ink) 3%, transparent); .k-value-ic { flex: none; - color: var(--tb-ink-54); - } - - .k-value-l { - flex: none; - font-size: var(--chat-meta); - color: var(--tb-ink-76); - } - - .k-value-v { - flex: 1; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-family: var(--tb-mono); - font-size: 13px; - background: none; - color: var(--tb-ink); - } - - .k-value-b.mat-mdc-icon-button { - --mdc-icon-button-state-layer-size: 32px; - --mat-icon-button-state-layer-size: 32px; - width: 32px; - height: 32px; - padding: 0; - flex: none; - color: var(--tb-ink-54); - display: inline-flex; - align-items: center; - justify-content: center; + color: rgba(255, 255, 255, 0.42); } } @@ -6851,31 +6920,102 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { .k-wait { display: flex; - align-items: center; + align-items: flex-start; gap: 8px; font-family: var(--tb-mono); - font-size: 13.5px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); color: var(--tb-text-secondary); tb-ai-spin { - --spin: 18px; + --spin: 20px; flex: none; } .clock { - margin-left: auto; - color: var(--tb-ink-54); + color: var(--k-faint); font-variant-numeric: tabular-nums; } + .k-wait-tools { + display: inline-flex; + gap: 2px; + margin: -2px 0 -2px auto; + } + + .k-wait-tool { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: var(--tb-ink-38); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus, var(--ai-deep)); + outline-offset: 1px; + } + } + + &:hover .k-wait-tool { + color: var(--tb-ink-76); + } + &.warn { + align-items: center; color: var(--tb-caution-text); + + > span:not(.clock):not(.mat-icon) { + font-family: var(--tb-font); + font-weight: 500; + } + + .mat-icon { + color: var(--tb-caution); + } } } .k-quiet { display: grid; gap: 8px; + + .ob-hint { + margin: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .k-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 2px; + } + + .ob-chip { + height: 28px; + padding: 0 10px; + font-size: var(--chat-line); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + } } } @@ -6908,3 +7048,27 @@ img.tb-ai-fade-in { opacity: 1; } } + +.k-fact-chip { + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + box-sizing: border-box; + padding: 0 8px 0 6px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--tb-line); + line-height: 22px; + white-space: nowrap; + + img { + width: 16px; + height: 16px; + object-fit: contain; + } + + .mat-icon { + color: var(--tb-ink-54); + } +} From 85a6b767cad0888c5268964fa36e3f340a98a5c8 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 26 Nov 2026 19:34:49 +0200 Subject: [PATCH 170/183] feat: AI hand-over card: Test from this computer first with the command in OS tabs and What you should see, Send a test value under the wait line, and a choice whose picked option rewrites the steps; fences can name a file or a tab (```bash tab=macOS), consecutive tabbed fences become one block with tabs in replies and cards, and a file block shows its name with Download --- .../home/components/ai/ai-action.models.ts | 70 ++++++++++---- .../ai/ai-chat-messages.component.ts | 4 +- .../home/components/ai/ai-code-block.ts | 94 +++++++++++++++---- .../components/ai/ai-hand-over.component.html | 48 +++++++++- .../components/ai/ai-hand-over.component.ts | 82 ++++++++++++++-- .../assets/locale/locale.constant-en_US.json | 7 ++ ui-ngx/src/theme/ai-theme.scss | 90 ++++++++++++++++++ 7 files changed, 347 insertions(+), 48 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index bb6232e992..4f04ee7647 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -322,6 +322,7 @@ export interface AiHandOverOption { label: string; icon?: string; text: string; + steps?: AiHandOverStep[]; } export interface AiHandOver { @@ -332,6 +333,38 @@ export interface AiHandOver { waitFor?: 'message' | 'uplink' | 'gateway'; intervalSeconds?: number; quiet?: string; + test?: AiHandOverTest; +} + +export interface AiHandOverTest { + hint?: string; + commands: {os: 'macos' | 'windows' | 'linux'; command: string}[]; + outcomes: {output: string; meaning: string; ok: boolean}[]; + sample?: Record; + accessToken?: string; +} + +function handOverTestOf(value: any): AiHandOverTest | undefined { + const commands = (Array.isArray(value?.commands) ? value.commands : []) + .filter(item => ['macos', 'windows', 'linux'].includes(item?.os) && text(item?.command)) + .slice(0, 3) + .map(item => ({os: item.os, command: item.command.trim()})); + if (!commands.length) { + return undefined; + } + const outcomes = (Array.isArray(value.outcomes) ? value.outcomes : []) + .filter(item => text(item?.output) && text(item?.meaning)) + .slice(0, 4) + .map(item => ({output: text(item.output), meaning: text(item.meaning), ok: item.ok === true})); + let sample: Record | undefined; + try { + const parsed = typeof value.sample === 'string' ? JSON.parse(value.sample) : value.sample; + sample = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined; + } catch { + sample = undefined; + } + const accessToken = text(value.accessToken); + return {hint: text(value.hint), commands, outcomes, ...(sample && accessToken ? {sample, accessToken} : {})}; } const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; @@ -346,25 +379,12 @@ export function aiHandOverOf(args: unknown): AiHandOver | null { if (!title) { return null; } - const steps: AiHandOverStep[] = (Array.isArray(values.steps) ? values.steps : []) - .filter(step => text(step?.title)) - .slice(0, 6) - .map(step => ({ - title: text(step.title), - detail: text(step.detail), - markdown: text(step.markdown), - done: step.done === true, - values: (Array.isArray(step.values) ? step.values : []) - .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) - .slice(0, 4) - .map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, - icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) - })); + const steps = handOverStepsOf(values.steps); const options: AiHandOverOption[] = (Array.isArray(values.choice?.options) ? values.choice.options : []) .filter(option => text(option?.id) && text(option?.label)) .slice(0, 4) .map(option => ({id: text(option.id), label: text(option.label), icon: typeof option.icon === 'string' && ICON_NAME.test(option.icon) ? option.icon : undefined, - text: text(option.text) ?? ''})); + text: text(option.text) ?? '', steps: handOverStepsOf(option.steps)})); const choice = options.length >= 2 ? { question: text(values.choice.question) ?? '', icon: iconOf(values.choice.icon, 'tune'), @@ -374,7 +394,25 @@ export function aiHandOverOf(args: unknown): AiHandOver | null { const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; const interval = Number(values.intervalSeconds); return {title, text: text(values.text), choice, steps, waitFor, - intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet)}; + intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet), + test: handOverTestOf(values.test)}; +} + +function handOverStepsOf(list: unknown): AiHandOverStep[] { + return (Array.isArray(list) ? list : []) + .filter(step => text(step?.title)) + .slice(0, 6) + .map(step => ({ + title: text(step.title), + detail: text(step.detail), + markdown: text(step.markdown), + done: step.done === true, + values: (Array.isArray(step.values) ? step.values : []) + .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) + .slice(0, 4) + .map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, + icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) + })); } export interface AiConnectionCheck { 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 fa86f5628a..0cd36b63ab 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 @@ -62,7 +62,7 @@ export interface AnswerReportEvent { problem: AnswerProblem; comment?: string; } -import { announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; +import { aiFenceMeta, announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; import { AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; import { aiDetailNames, AiDetailNames } from '@home/components/ai/ai-action-detail.models'; import { decorateFileChips, decorateHints, decorateLinks, decorateReferences, decorateSeverities, decorateValues } from '@home/components/ai/ai-references'; @@ -1032,7 +1032,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { '```'; } } else { - return msg; + return aiFenceMeta(msg); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts index 245130e19a..a76fb18f3e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -65,6 +65,8 @@ export function fileLanguage(name: string): CodeLanguage { } export function decorateCodeBlocks(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + readFenceMeta(root); + mergeTabs(root, translate, copy); root.querySelectorAll('pre').forEach(pre => { if (!pre.closest('.tb-codeblock')) { decorate(pre, translate, copy); @@ -72,10 +74,12 @@ export function decorateCodeBlocks(root: HTMLElement, translate: TranslateServic }); } -export function aiFileFences(markdown: string): {text: string; files: string[]} { - const files: string[] = []; +const FENCE_META = '\u2063tb:'; +const OS_TABS: Record = {macos: 'macos', mac: 'macos', windows: 'windows', linux: 'linux'}; + +export function aiFenceMeta(markdown: string): string { let open: string | null = null; - const text = (markdown ?? '').split('\n').map(line => { + return (markdown ?? '').split('\n').map(line => { const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line); if (!fence) { return line; @@ -88,26 +92,84 @@ export function aiFileFences(markdown: string): {text: string; files: string[]} } open = fence[2]; const info = fence[3].trim(); - const words = info.split(/\s+/); + const tab = /(?:^|\s)tab=(.+)$/.exec(info)?.[1]?.trim(); + const words = info.replace(/(?:^|\s)tab=.+$/, '').trim().split(/\s+/).filter(Boolean); const fileOf = (word: string) => /^[\w.-]+\.\w+$/.test(word ?? '') ? word : null; - const name = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); - files.push(name ?? ''); - if (!name) { + const file = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); + if (!file && !tab) { return line; } - const lang = words.length > 1 ? words[0] : fileLanguage(name).lang; - return fence[1] + fence[2] + lang; + const lang = words.length > 1 || !file ? (words[0] ?? '') : fileLanguage(file).lang; + const meta = JSON.stringify({...(file ? {file} : {}), ...(tab ? {tab} : {})}); + return fence[1] + fence[2] + lang + '\n' + FENCE_META + encodeURIComponent(meta); }).join('\n'); - return {text, files}; } -export function labelFileBlocks(root: HTMLElement, files: string[]): void { - root.querySelectorAll('pre > code').forEach((code, index) => { - const name = files[index]; - if (name && !code.hasAttribute('data-file')) { - code.setAttribute('data-file', name); - code.setAttribute('data-label', name); +function readFenceMeta(root: HTMLElement): void { + root.querySelectorAll('pre > code').forEach(code => { + const text = code.textContent ?? ''; + if (!text.startsWith(FENCE_META)) { + return; + } + const end = text.indexOf('\n'); + let meta: {file?: string; tab?: string} = {}; + try { + meta = JSON.parse(decodeURIComponent(text.slice(FENCE_META.length, end < 0 ? text.length : end))); + } catch { + meta = {}; + } + code.textContent = end < 0 ? '' : text.slice(end + 1); + if (meta.file) { + code.setAttribute('data-file', meta.file); + code.setAttribute('data-label', meta.file); + } + if (meta.tab) { + code.setAttribute('data-tab', meta.tab); + } + }); +} + +function mergeTabs(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const unitOf = (pre: Element): Element => { + const parent = pre.parentElement; + return parent && parent !== root && parent.tagName === 'DIV' && !/tb-markdown-view/.test(parent.className) + && parent.querySelectorAll(':scope > pre').length === 1 ? parent : pre; + }; + const pres = Array.from(root.querySelectorAll('pre')).filter(pre => pre.querySelector('code[data-tab]') && !pre.closest('.tb-codeblock')); + const used = new Set(); + pres.forEach(first => { + if (used.has(first)) { + return; + } + const group = [first]; + let next = unitOf(first).nextElementSibling; + while (next) { + const pre = next.matches('pre') ? next : next.querySelector(':scope > pre'); + if (!pre || !pre.querySelector('code[data-tab]')) { + break; + } + group.push(pre as HTMLPreElement); + next = unitOf(pre).nextElementSibling; + } + group.forEach(pre => used.add(pre)); + if (group.length < 2) { + return; } + const tabs: CodeTab[] = group.map(pre => { + const code = pre.querySelector('code'); + const label = code.getAttribute('data-tab'); + const lang = /(?:^|\s)language-([\w+#-]+)/.exec(code.className)?.[1]?.toLowerCase(); + return {id: OS_TABS[label.toLowerCase()] ?? label, label, text: (code.textContent ?? '').replace(/\n$/, ''), lang}; + }); + const os = tabs.every(tab => Object.values(OS_TABS).includes(tab.id)); + const key = os ? 'os' : 'tabs:' + tabs.map(tab => tab.id).join('|'); + const local = /Windows/i.test(navigator.userAgent) ? 'windows' : /Mac/i.test(navigator.userAgent) ? 'macos' : 'linux'; + const preferred = codeTabGroup(key) ?? (os ? local : null); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + const block = codeTabsBlock(tabs, tabs[0].lang ?? 'shell', translate, copy, initial, undefined, {group: key}); + const anchor = unitOf(group[0]); + anchor.parentNode.insertBefore(block, anchor); + group.forEach(pre => unitOf(pre).remove()); }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html index 1df2219ef4..c7a4c55355 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -26,7 +26,7 @@ }
    @if (handOver().text) { - + } @if (handOver().choice; as choice) {
    @@ -45,13 +45,13 @@
    @if (choiceText()) { -
    +
    }
    } - @if (handOver().steps.length) { + @if (steps().length) {
      - @for (step of handOver().steps; track $index; let i = $index) { + @for (step of steps(); track step; let i = $index) {
    } + @if (handOver().test; as test) { + + @if (test.hint) { +

    {{ test.hint }}

    + } +
    + @if (test.outcomes.length) { + +
    + @for (outcome of test.outcomes; track $index) { + + + + + } +
    {{ outcome.output }}{{ outcome.meaning }}
    + + } + + } @if (quiet() || stoppedQuiet()) {
    @@ -104,6 +124,11 @@

    {{ handOver().quiet }}

    }
    + @if (canSendTest() && waiting()) { + + } @@ -113,6 +138,7 @@
    } @else if (waiting()) { +
    {{ waitLabel() }} @@ -125,6 +151,18 @@
    + @if (canSendTest()) { +
    + +
    + } + @if (testNote(); as note) { +

    {{ note }}

    + } +
    }
    } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index 9fc8279671..334a93ba87 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; import { Clipboard } from '@angular/cdk/clipboard'; import { TranslateService } from '@ngx-translate/core'; import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; -import { aiFileFences, announceCopied, decorateCodeBlocks, labelFileBlocks } from '@home/components/ai/ai-code-block'; +import { aiFenceMeta, announceCopied, codeTabGroup, codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; export interface AiHandOverWait { running: boolean; @@ -15,6 +15,13 @@ export interface AiHandOverWait { } const MIN_SILENCE_MS = 120000; +const TEST_MARKER = 'aiTestValue'; +const OS_LABELS: Record = {macos: 'macOS', windows: 'Windows', linux: 'Linux'}; + +function localOs(): string { + const platform = navigator.userAgent; + return /Windows/i.test(platform) ? 'windows' : /Mac/i.test(platform) ? 'macos' : 'linux'; +} const COPIED_MS = 1500; @Component({ @@ -22,7 +29,7 @@ const COPIED_MS = 1500; templateUrl: './ai-hand-over.component.html', standalone: false }) -export class AiHandOverComponent { +export class AiHandOverComponent implements AfterViewChecked { handOver = input.required(); wait = input(null); @@ -42,8 +49,15 @@ export class AiHandOverComponent { readonly copied = signal(null); readonly now = signal(Date.now()); readonly open = signal(false); + readonly testState = signal<'idle' | 'sending' | 'sent' | 'failed'>('idle'); + readonly testAt = signal(0); + readonly testError = signal(''); readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null); + readonly steps = computed(() => { + const picked = this.handOver().choice?.options.find(option => option.id === this.choiceValue()); + return picked?.steps?.length ? picked.steps : this.handOver().steps; + }); readonly choiceText = computed(() => this.handOver().choice?.options.find(option => option.id === this.choiceValue())?.text ?? ''); readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); @@ -55,6 +69,18 @@ export class AiHandOverComponent { }); readonly waiting = computed(() => !!this.wait()?.running); + readonly canSendTest = computed(() => !!this.handOver().test?.sample && this.handOver().waitFor === 'message'); + readonly testNote = computed(() => { + const time = new Date(this.testAt()).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + switch (this.testState()) { + case 'sent': + return this.translate.instant('ai-assistant.hand-over.test-sent', {time}); + case 'failed': + return this.translate.instant('ai-assistant.hand-over.test-failed', {error: this.testError()}); + default: + return ''; + } + }); readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); readonly clock = computed(() => { const seconds = Math.floor(this.elapsed() / 1000); @@ -77,6 +103,7 @@ export class AiHandOverComponent { inject(DestroyRef).onDestroy(() => clearInterval(timer)); effect(() => { this.choiceText(); + this.steps(); this.handOver(); this.folded(); setTimeout(() => this.decorate()); @@ -84,17 +111,29 @@ export class AiHandOverComponent { } md(text: string): string { - return aiFileFences(text).text; + return aiFenceMeta(text); } - files(text: string): string { - return aiFileFences(text).files.join('|'); + ngAfterViewChecked(): void { + if ((this.host.nativeElement as HTMLElement).querySelector('.k-test-slot:empty')) { + this.decorate(); + } } decorate(): void { const root = this.host.nativeElement as HTMLElement; - root.querySelectorAll('tb-markdown[data-files]').forEach(markdown => - labelFileBlocks(markdown, (markdown.dataset.files ?? '').split('|'))); + const test = this.handOver().test; + root.querySelectorAll('.k-test-slot:empty').forEach(slot => { + if (!test) { + return; + } + const order = ['macos', 'windows', 'linux']; + const tabs = [...test.commands].sort((a, b) => order.indexOf(a.os) - order.indexOf(b.os)).map(command => ({id: command.os, label: OS_LABELS[command.os], text: command.command, + lang: command.os === 'windows' ? 'powershell' : 'shell'})); + const preferred = codeTabGroup('os') ?? localOs(); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + slot.append(codeTabsBlock(tabs, 'shell', this.translate, text => this.clipboard.copy(text), initial, undefined, {group: 'os'})); + }); decorateCodeBlocks(root, this.translate, text => this.clipboard.copy(text)); } @@ -104,6 +143,7 @@ export class AiHandOverComponent { pick(id: string): void { this.picked.set(id); + this.ticked.set(new Set()); } tick(index: number): void { @@ -117,7 +157,7 @@ export class AiHandOverComponent { } done(index: number): boolean { - return this.ticked().has(index) !== (this.handOver().steps[index]?.done === true); + return this.ticked().has(index) !== (this.steps()[index]?.done === true); } reveal(key: string): void { @@ -142,6 +182,30 @@ export class AiHandOverComponent { } } + async sendTest(): Promise { + const test = this.handOver().test; + if (!test?.sample || !test.accessToken || this.testState() === 'sending') { + return; + } + this.testState.set('sending'); + const ts = Date.now(); + try { + const response = await fetch(`/api/v1/${encodeURIComponent(test.accessToken)}/telemetry`, { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ts, values: {...test.sample, [TEST_MARKER]: true}}) + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + this.testAt.set(ts); + this.testState.set('sent'); + } catch (error) { + this.testError.set(error instanceof Error ? error.message : String(error)); + this.testState.set('failed'); + } + } + say(key: string): void { this.prompt.emit(this.translate.instant(key)); } 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 db2adc302b..0f109ff7b2 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -2181,6 +2181,13 @@ }, "hand-over": { "stop-listening": "Stop listening", + "test-first": "Test from this computer first", + "what-you-see": "What you should see", + "send-test": "Send a test value", + "send-test-here": "Send a test value from here", + "send-test-tip": "Sends one value as the device, marked as a test; the wait keeps listening for the device itself", + "test-sent": "A test value went in at {{time}} and is on the device's latest telemetry. The wait keeps listening for the device itself.", + "test-failed": "The test value did not go through: {{error}}.", "needs-you": "Needs you", "fold": "Fold", "unfold": "Show the steps", diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index eaaa920f0d..58fab99af4 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -6986,6 +6986,96 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { } } + .k-waitrow { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 8px; + + .k-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + + .ob-chip { + height: 28px; + padding: 0 10px; + font-size: var(--chat-line); + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + } + } + } + + .k-test-note { + margin: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-76); + + &.warn { + color: var(--tb-caution-text); + } + } + + .k-test { + display: block; + + .ob-hint { + margin: 0 0 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .k-test-slot { + margin-bottom: 8px; + } + } + + .k-outcomes { + border-collapse: collapse; + width: 100%; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + + td { + padding: 6px 10px 6px 0; + border-top: 1px solid var(--tb-line-soft); + vertical-align: top; + color: var(--tb-ink-76); + } + + tr:first-child td { + border-top: 0; + } + + td:first-child { + width: 45%; + } + + code { + display: inline-block; + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + overflow-wrap: anywhere; + } + + tr.ok code { + color: var(--tb-ok-text); + } + + tr.warn code { + color: var(--tb-caution-text); + } + } + .k-quiet { display: grid; gap: 8px; From 6044477fcf6c5b348e705ddaba7405528a50f3f4 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 27 Nov 2026 12:04:28 +0200 Subject: [PATCH 171/183] feat: AI chat connectivity fixes from live testing: the nothing-heard row offers the case's own paste chip that fills the composer and reads 'It is on now, keep waiting', its threshold capped at five minutes; a file the assistant wrote sits inside the hand-over step that uses it; a wait that started before its card shows after it; a reloaded turn keeps each tool's start time; record cards waiting for data re-check until the device is active; a gateway's arrival reads that it connected and JSON values stay out of readings; expanding a disclosure, a folded code block, unchanged review fields or a done card scrolls it clear of the composer; every message sends the browser's operating system in the client context; long answers wrap in the answered-questions card --- .../services/ai-assistant-panel.service.ts | 6 +-- .../components/ai/ai-action-line.component.ts | 3 ++ .../home/components/ai/ai-action.models.ts | 23 +++++++++-- .../ai/ai-approval-card.component.html | 2 +- .../ai/ai-approval-card.component.ts | 8 ++++ .../ai/ai-assistant-context.service.ts | 4 +- .../ai/ai-chat-messages.component.html | 11 +++++- .../ai/ai-chat-messages.component.ts | 35 ++++++++++++++++- .../home/components/ai/ai-chat.component.ts | 12 +++--- .../home/components/ai/ai-code-block.ts | 4 ++ .../components/ai/ai-disclosure.component.ts | 39 ++++++++++++++++++- .../components/ai/ai-hand-over.component.html | 22 +++++++++-- .../components/ai/ai-hand-over.component.ts | 21 +++++++++- .../components/ai/ai-records.component.ts | 15 +++++-- .../src/app/shared/models/ai-chat.models.ts | 9 +++++ .../assets/locale/locale.constant-en_US.json | 3 +- ui-ngx/src/theme/ai-theme.scss | 10 +++++ 17 files changed, 198 insertions(+), 29 deletions(-) diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index 69f29d3248..e45637b55a 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts @@ -5,7 +5,7 @@ import { defer, Observable, Subject } from 'rxjs'; import { distinctUntilChanged, filter, finalize, map } from 'rxjs/operators'; import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, AiChatView, ChatInfo, AiPromptMessage } from '@shared/models/ai-chat.models'; +import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, ChatInfo, AiPromptMessage } from '@shared/models/ai-chat.models'; import { EntityId } from '@shared/models/id/entity-id'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { LocalStorageService } from '@core/local-storage/local-storage.service'; @@ -397,7 +397,7 @@ export class AiAssistantPanelService implements OnDestroy { } setClientContextForView(view: AiChatView): void { - this.setClientContext({view, timeZone: getDefaultTimezone()}); + this.setClientContext({view, timeZone: getDefaultTimezone(), os: aiClientOs()}); } focusWhile(view: AiChatView, name: string | null | undefined, until: Observable): Observable { @@ -406,7 +406,7 @@ export class AiAssistantPanelService implements OnDestroy { if (!previous || !view.entityId?.id) { return until; } - const focus = {context: {view, timeZone: getDefaultTimezone()}, previous, previousName: this._viewName()}; + const focus = {context: {view, timeZone: getDefaultTimezone(), os: aiClientOs()}, previous, previousName: this._viewName()}; this._focus = focus; this._clientContext.set(focus.context); this._viewName.set(name?.trim() || null); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index b805eae38a..7b165268f1 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -126,6 +126,9 @@ export class AiActionLineComponent { return null; } const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + if (check.gateway) { + return {text: this.translate.instant('ai-assistant.hand-over.gateway-connected', {name: check.name, time}), readings: []}; + } return { text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys') + (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}), diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index 4f04ee7647..ae6d8ebffd 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -314,6 +314,7 @@ export interface AiHandOverStep { detail?: string; markdown?: string; values: AiHandOverValue[]; + file?: string; done: boolean; } @@ -334,6 +335,7 @@ export interface AiHandOver { intervalSeconds?: number; quiet?: string; test?: AiHandOverTest; + paste?: {label: string; icon: string; intro: string}; } export interface AiHandOverTest { @@ -395,7 +397,13 @@ export function aiHandOverOf(args: unknown): AiHandOver | null { const interval = Number(values.intervalSeconds); return {title, text: text(values.text), choice, steps, waitFor, intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet), - test: handOverTestOf(values.test)}; + test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)}; +} + +function handOverPasteOf(value: any): AiHandOver['paste'] { + const label = text(value?.label); + const intro = text(value?.intro); + return label && intro ? {label, intro, icon: iconOf(value.icon, 'terminal')} : undefined; } function handOverStepsOf(list: unknown): AiHandOverStep[] { @@ -406,6 +414,7 @@ function handOverStepsOf(list: unknown): AiHandOverStep[] { title: text(step.title), detail: text(step.detail), markdown: text(step.markdown), + file: text(step.file), done: step.done === true, values: (Array.isArray(step.values) ? step.values : []) .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) @@ -422,6 +431,7 @@ export interface AiConnectionCheck { note?: string; readings: {key: string; value: string}[]; keyCount: number; + gateway: boolean; } export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { @@ -438,11 +448,16 @@ export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { } const readings: {key: string; value: string}[] = []; const add = (telemetry: unknown) => Object.entries(telemetry && typeof telemetry === 'object' ? telemetry : {}) - .forEach(([key, item]) => readings.push({key, value: String((item as any)?.value ?? '')})); - add(values.telemetry); + .map(([key, item]) => ({key, value: String((item as any)?.value ?? '')})) + .filter(reading => !/^\s*[{[]/.test(reading.value)) + .forEach(reading => readings.push(reading)); + const gateway = values.gateway === true; + if (!gateway) { + add(values.telemetry); + } (Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), - note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size}; + note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size, gateway}; } export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index f59b3e2b60..0bdcc75eda 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -79,7 +79,7 @@ } @if (unchanged.length) { - diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 82c5597d31..53936ba4fa 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -13,6 +13,7 @@ import { SimpleChanges, ViewChild } from '@angular/core'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; import { TranslateService } from '@ngx-translate/core'; import { ClipboardService } from 'ngx-clipboard'; import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; @@ -368,6 +369,13 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { return this.state === 'pending' || this.state === 'denied' || this.state === 'expired'; } + toggleUnchanged(): void { + this.showUnchanged = !this.showUnchanged; + if (this.showUnchanged) { + aiRevealOpened(this.host.nativeElement); + } + } + approve(): void { this.state = this.autoApproved ? 'auto' : 'approved'; this.denying = false; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts index f17294b9d0..cd8cdc97b8 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts @@ -5,7 +5,7 @@ import { toSignal } from '@angular/core/rxjs-interop'; import { NavigationEnd, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { filter, map, startWith } from 'rxjs/operators'; -import { aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models'; +import { aiClientOs, aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { BreadCrumb } from '@shared/components/breadcrumb'; import { BreadcrumbService } from '@core/services/breadcrumb.service'; @@ -41,7 +41,7 @@ export class AiAssistantContextService { const title = this.pageTitle(); const path = this.pagePath(); const type = aiPageView(path); - return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone()} : undefined; + return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone(), os: aiClientOs()} : undefined; }); readonly welcome = computed(() => aiWelcome(this.clientContext()?.view, this.panelService.viewName(), this.panelService.config(), 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 289e1aafa0..525a62f5b7 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 @@ -54,6 +54,7 @@ }
    + } @else if (msg.from === 'ACTION' && files[$index] && inCard.has(files[$index].name)) { } @else if (msg.from === 'ACTION' && files[$index]; as file) {

    {{ arrivedLine() }}

    } @else { @@ -60,6 +60,14 @@ {{ step.detail }} } + @if (step.file && files().get(step.file); as file) { + + } @if (step.values.length || step.markdown) {
    @for (value of step.values; track $index; let v = $index) { @@ -132,9 +140,15 @@ - + @if (handOver().paste; as paste) { + + } @else { + + }
    } @else if (waiting()) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index 334a93ba87..3b7c7c7767 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; import { Clipboard } from '@angular/cdk/clipboard'; import { TranslateService } from '@ngx-translate/core'; import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; @@ -15,6 +17,7 @@ export interface AiHandOverWait { } const MIN_SILENCE_MS = 120000; +const MAX_SILENCE_MS = 300000; const TEST_MARKER = 'aiTestValue'; const OS_LABELS: Record = {macos: 'macOS', windows: 'Windows', linux: 'Linux'}; @@ -34,10 +37,16 @@ export class AiHandOverComponent implements AfterViewChecked { handOver = input.required(); wait = input(null); time = input(0); + files = input>(new Map()); @Output() prompt = new EventEmitter(); @Output() stop = new EventEmitter(); + @Output() compose = new EventEmitter(); + @Output() openFile = new EventEmitter(); + + readonly fileMark = aiFileMark; + readonly fileName = aiFileName; private host = inject(ElementRef); private translate = inject(TranslateService); @@ -86,7 +95,8 @@ export class AiHandOverComponent implements AfterViewChecked { const seconds = Math.floor(this.elapsed() / 1000); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; }); - readonly silenceMs = computed(() => Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0))); + readonly silenceMs = computed(() => Math.min(MAX_SILENCE_MS, + Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0)))); readonly quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs()); readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000))); readonly stoppedQuiet = computed(() => { @@ -206,6 +216,15 @@ export class AiHandOverComponent implements AfterViewChecked { } } + unfold(): void { + this.open.set(true); + aiRevealOpened(this.host.nativeElement); + } + + startPaste(intro: string): void { + this.compose.emit(intro + '\n'); + } + say(key: string): void { this.prompt.emit(this.translate.instant(key)); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts index 4107ed8a6a..212630cc6b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts @@ -3,7 +3,8 @@ import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { TranslateService } from '@ngx-translate/core'; -import { Subscription } from 'rxjs'; +import { Subscription, timer } from 'rxjs'; +import { concatMap, take, takeWhile } from 'rxjs/operators'; import { aiEntityKind } from '@home/components/ai/ai-action.models'; import { aiRecordKey, AiRecordView, AiShownRecords } from '@home/components/ai/ai-record.models'; import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; @@ -16,6 +17,9 @@ const LIST_SHOWN = 8; const TARGETED_HUB_TYPES = new Set([ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE]); +const WAIT_RECHECK_MS = 10000; +const WAIT_RECHECKS = 90; + @Component({ selector: 'tb-ai-records', template: ` @@ -125,9 +129,12 @@ export class AiRecordsComponent { this.key(); const shown = untracked(() => this.shown()); this.loading?.unsubscribe(); - this.loading = this.loader.loadAll(shown.refs, {image: shown.refs.length === 1}) - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(views => this.views.set(views)); + this.loading = timer(0, WAIT_RECHECK_MS).pipe( + take(WAIT_RECHECKS), + concatMap(() => this.loader.loadAll(shown.refs, {image: shown.refs.length === 1})), + takeWhile(views => views.some(view => view.state?.tone === 'wait'), true), + takeUntilDestroyed(this.destroyRef) + ).subscribe(views => this.views.set(views)); }); } 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 984b1b0af8..dcbad75537 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -187,6 +187,7 @@ export interface TurnStoppedEvent extends BaseChatEvent { export interface ToolStarted extends BaseChatToolEventData { tool: string; arguments?: unknown; + startedAt?: number; } export interface ToolStartedEvent extends BaseChatEvent { @@ -461,6 +462,14 @@ export interface AiChatView { export interface AiChatClientContext { view: AiChatView; timeZone?: string; + os?: string; +} + +export function aiClientOs(): string | undefined { + const nav = navigator as Navigator & {userAgentData?: {platform?: string}}; + const agent = `${nav.userAgentData?.platform ?? ''} ${navigator.userAgent}`; + return /Android/i.test(agent) ? 'android' : /iPhone|iPad|iPod/i.test(agent) ? 'ios' : /CrOS|Chrome OS/i.test(agent) ? 'chromeos' + : /Win/i.test(agent) ? 'windows' : /Mac/i.test(agent) ? 'macos' : /Linux|X11/i.test(agent) ? 'linux' : undefined; } export interface SendChatMessageRequest { 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 0f109ff7b2..b67b7ee1e4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -2191,6 +2191,7 @@ "needs-you": "Needs you", "fold": "Fold", "unfold": "Show the steps", + "gateway-connected": "{{name}} connected at {{time}}.", "arrived-message": "The first message arrived at {{time}}.", "arrived-message-from": "The first message from {{name}} arrived at {{time}}.", "arrived-uplink": "The first uplink arrived at {{time}}.", @@ -2208,7 +2209,7 @@ "wait-uplink": "listening for the first uplink", "wait-gateway": "listening for the gateway", "nothing-heard": "nothing heard for {{minutes}} min", - "keep-waiting": "It is on, keep waiting", + "keep-waiting": "It is on now, keep waiting", "keep-waiting-prompt": "It is on. Keep waiting for the data.", "what-wrong": "What could be wrong?", "what-wrong-prompt": "Nothing arrived. What could be wrong?" diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 58fab99af4..916b8a9123 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -2282,9 +2282,12 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); } display: flex; flex-wrap: wrap; gap: 8px; + min-width: 0; } .ob-chip[aria-pressed="true"] { + max-width: 100%; + overflow-wrap: anywhere; height: auto; min-height: 0; padding: 0; @@ -6832,6 +6835,13 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { text-decoration-color: var(--tb-ink-38); } + .k-step-file { + display: flex; + width: auto; + max-width: calc(100% - 28px); + margin: 8px 0 2px 28px; + } + .k-step-x { margin: 8px 0 2px 28px; min-width: 0; From 5318a6d4917b4d1a9cd31a8c1a6564f9c10c6b96 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 27 Nov 2026 12:40:50 +0200 Subject: [PATCH 172/183] fix: a hand-over whose wait ended on uplinks the converter did not decode says so instead of 'nothing heard' and leaves out the nothing-arrived causes --- .../modules/home/components/ai/ai-hand-over.component.html | 4 ++-- .../app/modules/home/components/ai/ai-hand-over.component.ts | 1 + ui-ngx/src/assets/locale/locale.constant-en_US.json | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html index 031a8bf35b..14d755c04e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -123,12 +123,12 @@
    - {{ 'ai-assistant.hand-over.nothing-heard' | translate: {minutes: quietMinutes()} }} + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }} @if (waiting()) { {{ clock() }} }
    - @if (handOver().quiet) { + @if (handOver().quiet && !undecoded()) {

    {{ handOver().quiet }}

    }
    diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index 3b7c7c7767..f200bea2c7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -99,6 +99,7 @@ export class AiHandOverComponent implements AfterViewChecked { Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0)))); readonly quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs()); readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000))); + readonly undecoded = computed(() => this.wait()?.check?.failedStep === 'decoded'); readonly stoppedQuiet = computed(() => { const wait = this.wait(); return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; 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 b67b7ee1e4..637b70f690 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -2209,6 +2209,7 @@ "wait-uplink": "listening for the first uplink", "wait-gateway": "listening for the gateway", "nothing-heard": "nothing heard for {{minutes}} min", + "not-decoded": "uplinks arrived but were not decoded", "keep-waiting": "It is on now, keep waiting", "keep-waiting-prompt": "It is on. Keep waiting for the data.", "what-wrong": "What could be wrong?", From 105d48b1135bf9f74128954c425f11451b82effa Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 27 Nov 2026 14:26:45 +0200 Subject: [PATCH 173/183] feat: V4_4_2_0Migration creates the AI credits limit increase request notification template when the system tenant has none, so installations patched within 4.4 (which never run updateDefaultNotificationConfigs) can send the request; 4.4.2.0 ships no SQL and is listed in SQL_LESS_ALLOWED --- .../install/lts/V4_4_2_0Migration.java | 41 ++++++++++++++ .../install/lts/MigrationIntegrationTest.java | 4 +- .../install/lts/V4_4_2_0MigrationTest.java | 56 +++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java new file mode 100644 index 0000000000..4c7a4dbeb4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class V4_4_2_0Migration implements Migration { + + private final NotificationSettingsService notificationSettingsService; + private final DefaultNotifications defaultNotifications; + + @Override + public String getVersion() { + return "4.4.2.0"; + } + + @Override + public void apply() { + createAiCreditsLimitIncreaseRequestTemplate(); + } + + private void createAiCreditsLimitIncreaseRequestTemplate() { + if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) { + log.debug("The AI credits limit increase request notification template already exists"); + return; + } + defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + log.info("Created the AI credits limit increase request notification template"); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java index bbdb95c466..0d557be89b 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java @@ -57,9 +57,9 @@ public class MigrationIntegrationTest extends AbstractControllerTest { private static final String SCHEMA_UPDATE_SQL = "schema_update.sql"; // Versions with a registered bean but no schema_update.sql, because their whole change is programmatic: - // 4.3.1.5 rewrites one JSON column through the DAO. Entries here opt out of the dir/bean check below, + // 4.3.1.5 rewrites one JSON column through the DAO, 4.4.2.0 adds a notification template. Entries here opt out of the dir/bean check below, // so add one only when the version genuinely ships no SQL. - private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5"); + private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5", "4.4.2.0"); @Autowired private MigrationService migrationService; diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java new file mode 100644 index 0000000000..37dc7bd57e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class V4_4_2_0MigrationTest { + + @Mock + private NotificationSettingsService notificationSettingsService; + @Mock + private DefaultNotifications defaultNotifications; + + @InjectMocks + private V4_4_2_0Migration migration; + + @Test + void hasItsVersion() { + assertEquals("4.4.2.0", migration.getVersion()); + } + + @Test + void createsAiCreditsLimitIncreaseRequestTemplateWhenMissing() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(false); + + migration.apply(); + + verify(defaultNotifications).create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + } + + @Test + void keepsAiCreditsLimitIncreaseRequestTemplateWhenPresent() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(true); + + migration.apply(); + + verify(defaultNotifications, never()).create(any(), any()); + } +} From 079271a98d8e7039a307aa986a227c0f1bee6fa8 Mon Sep 17 00:00:00 2001 From: Artem Babak Date: Fri, 27 Nov 2026 17:14:25 +0200 Subject: [PATCH 174/183] fix: hide dashboards marked hidden for mobile in dashboard select inside the mobile app (#16797) The dashboard selection dropdown requested /api/user/dashboards without the mobile flag, so dashboards with "Hide dashboard in mobile application" were listed and could be opened from the mobile app. Pass mobile=true when the UI runs inside the mobile app; browser behaviour is unchanged. --- ui-ngx/src/app/core/http/dashboard.service.ts | 5 ++++- .../src/app/shared/components/dashboard-select.component.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/core/http/dashboard.service.ts b/ui-ngx/src/app/core/http/dashboard.service.ts index 15c2501a76..30608a5b75 100644 --- a/ui-ngx/src/app/core/http/dashboard.service.ts +++ b/ui-ngx/src/app/core/http/dashboard.service.ts @@ -60,7 +60,7 @@ export class DashboardService { } public getUserDashboards(userId: string, operation: Operation, - pageLink: PageLink, config?: RequestConfig): Observable> { + pageLink: PageLink, config?: RequestConfig, mobile = false): Observable> { let url = `/api/user/dashboards${pageLink.toQuery()}`; if (userId) { url += `&userId=${userId}`; @@ -68,6 +68,9 @@ export class DashboardService { if (operation) { url += `&operation=${operation}`; } + if (mobile) { + url += `&mobile=true`; + } return this.http.get>(url, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/shared/components/dashboard-select.component.ts b/ui-ngx/src/app/shared/components/dashboard-select.component.ts index ea13a3fa4c..1cf971914e 100644 --- a/ui-ngx/src/app/shared/components/dashboard-select.component.ts +++ b/ui-ngx/src/app/shared/components/dashboard-select.component.ts @@ -37,6 +37,7 @@ import { } from './dashboard-select-panel.component'; import { Operation } from '@shared/models/security.models'; import { UtilsService } from '@core/services/utils.service'; +import { MobileService } from '@core/services/mobile.service'; // @dynamic @Component({ @@ -87,6 +88,7 @@ export class DashboardSelectComponent implements ControlValueAccessor, OnInit { constructor(private store: Store, private dashboardService: DashboardService, private utils: UtilsService, + private mobileService: MobileService, private overlay: Overlay, private breakpointObserver: BreakpointObserver, private viewContainerRef: ViewContainerRef, @@ -185,7 +187,8 @@ export class DashboardSelectComponent implements ControlValueAccessor, OnInit { if (this.customerId) { dashboardsObservable = this.dashboardService.getCustomerDashboards(true, this.customerId, pageLink, {ignoreLoading: true}); } else { - dashboardsObservable = this.dashboardService.getUserDashboards(null, this.operation, pageLink, {ignoreLoading: true}); + dashboardsObservable = this.dashboardService.getUserDashboards(null, this.operation, pageLink, {ignoreLoading: true}, + this.mobileService.isMobileApp()); } } return dashboardsObservable; From bb58609601ef63c5470606b97077e4bcb83b290b Mon Sep 17 00:00:00 2001 From: Serhii Titenko Date: Fri, 27 Nov 2026 17:16:19 +0200 Subject: [PATCH 175/183] Fixed downlink fields staying required in the Add integration wizard after choosing Skip (#16795) * Showed Azure Event Hub IoT Hub name only with a downlink converter The IoT Hub name field is used only to send cloud-to-device messages, so the form shows it only when the integration has a downlink converter. The add-integration wizard counted a converter chosen under "Select existing" even after switching to "Skip", and did not count "Library"; it now uses only the current choice, which also fixes the downlink fields of UDP, TCP, KPN, ChirpStack and Azure Service Bus. Required-field messages on the form now read as full sentences. * Moved downlink converter check in the wizard to a getter The add-integration wizard now decides whether a downlink converter is set in isDownlinkConverterSet, next to createDownlinkConverter(). --- ...-event-hub-integration-form.component.html | 20 ++++++++++--------- .../integration-wizard-dialog.component.html | 2 +- .../integration-wizard-dialog.component.ts | 11 ++++++++++ .../assets/locale/locale.constant-en_US.json | 10 +++++----- 4 files changed, 28 insertions(+), 15 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html index 1bcad7d9c1..bd66080687 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html @@ -12,15 +12,17 @@ label="{{ 'integration.connection-string' | translate }}" requiredText="{{ 'integration.connection-string-required' | translate }}"> - - integration.iot-hub-name - - @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { - - integration.event-iot-hub-name-required - - } - + @if (isSetDownLink) { + + integration.iot-hub-name + + @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { + + integration.event-iot-hub-name-required + + } + + } diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html index c3047766af..c210b855ff 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html @@ -163,7 +163,7 @@ [genericAdditionalInfoTemplate]="genericAdditionalInfo" [executeRemotelyTemplate]="executeRemotely" [integrationType]="integrationWizardForm.get('type').value" - [isSetDownlink]="!!downlinkConverterForm.get('downlinkConverterId').value || downlinkConverterForm.get('converterType').value === 'new'" + [isSetDownlink]="isDownlinkConverterSet" [isEdgeTemplate]="isEdgeTemplate" > diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts index fc73da1626..bd1e829cdf 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts @@ -283,6 +283,17 @@ export class IntegrationWizardDialogComponent extends } } + get isDownlinkConverterSet(): boolean { + switch (this.downlinkConverterForm.get('converterType').value) { + case ConverterSourceType.EXISTING: + return !!this.downlinkConverterForm.get('downlinkConverterId').value; + case ConverterSourceType.SKIP: + return false; + default: + return true; + } + } + private createDownlinkConverter(): Observable { const converterType = this.downlinkConverterForm.get('converterType').value; if (converterType === ConverterSourceType.SKIP) { 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 03f4ec89ad..514adbfc90 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -5683,21 +5683,21 @@ "service-bus-namespace-name-required": "Service Bus Namespace Name is required.", "connection-string": "Connection string", "consumer-group": "Consumer group", - "connection-string-required": "Connection string required!", + "connection-string-required": "Connection string is required.", "event-hub-name": "Event Hub Name", "event-hub-name-required": "Event Hub Name is required.", - "event-iot-hub-name-required": "Iot Hub Name is required for downlink", + "event-iot-hub-name-required": "IoT Hub name is required.", "enable-persistent-checkpoints": "Enable persistent checkpoints", "enable-persistent-checkpoints-hint": "Enable Azure Blob Storage to resume processing from the last checkpoint after a restart. Disable to always start from the latest event.", "storage-connection-string": "Storage connection string", - "storage-connection-string-required": "Storage connection string is required!", + "storage-connection-string-required": "Storage connection string is required.", "container-name": "Container name", - "container-name-required": "Container name is required", + "container-name-required": "Container name is required.", "sas-key-name": "SAS Key Name", "sas-key-name-required": "SAS Key Name is required.", "sas-key": "SAS Key", "sas-key-required": "SAS Key is required.", - "iot-hub-name": "IoT Hub Name", + "iot-hub-name": "IoT Hub name", "hostname": "Hostname", "hostname-required": "Hostname is required", "integration-clazz": "Integration class", From 5ec5a96f074db1d4abca6bf308d7b731b1bb8474 Mon Sep 17 00:00:00 2001 From: Serhii Titenko Date: Fri, 27 Nov 2026 17:17:40 +0200 Subject: [PATCH 176/183] Showed Azure Service Bus downlink fields only with a downlink converter (#16801) The Downlink connection string and Downlink topic name fields are used only to send downlinks, but were shown for every integration in the collapsed Advanced settings, and stayed there when a downlink converter made them required. They are now shown below the topic and subscription only when a downlink converter is set. Required-field messages of the form end with a period. --- ...rvices-bus-integration-form.component.html | 31 +++++++++---------- .../assets/locale/locale.constant-en_US.json | 8 ++--- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html index 6e3cde027c..d48883be07 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html @@ -29,6 +29,21 @@ }
    + @if (isSetDownLink) { + + + + integration.downlink-topic-name + + @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { + integration.downlink-topic-name-required + } + + } @@ -40,22 +55,6 @@ - - - - - integration.downlink-topic-name - - @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { - - integration.downlink-topic-name-required - - } - - 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 514adbfc90..7d7317dae7 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -5968,13 +5968,13 @@ "region-eu": "Europe", "region-in": "India", "topic-name": "Topic name", - "topic-name-required": "Topic name is required", + "topic-name-required": "Topic name is required.", "sub-name": "Subscription name", - "sub-name-required": "Subscription name is required", + "sub-name-required": "Subscription name is required.", "downlink-connection-string": "Downlink connection string", - "downlink-connection-string-required": "Downlink connection string is required", + "downlink-connection-string-required": "Downlink connection string is required.", "downlink-topic-name": "Downlink topic name", - "downlink-topic-name-required": "Downlink topic name is required" + "downlink-topic-name-required": "Downlink topic name is required." }, "scada": { "symbols": "SCADA symbols", From 5340d727f830353c2f9476e36fc6284df2e13c13 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Fri, 27 Nov 2026 16:44:19 +0100 Subject: [PATCH 177/183] Fixed the Go to search showing the previous user's menu items after Login as or menu changes (#16840) * Fixed Go to menu search crashing after selecting a link * PR comments fixes --- .../src/app/modules/home/menu/goto-menu.component.html | 4 ++-- ui-ngx/src/app/modules/home/menu/goto-menu.component.ts | 9 ++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/ui-ngx/src/app/modules/home/menu/goto-menu.component.html b/ui-ngx/src/app/modules/home/menu/goto-menu.component.html index bba1ffe39a..41e8f677c5 100644 --- a/ui-ngx/src/app/modules/home/menu/goto-menu.component.html +++ b/ui-ngx/src/app/modules/home/menu/goto-menu.component.html @@ -45,7 +45,7 @@ @if (gotoMenuResult.hasMatches) { @if (gotoMenuResult.nameMatches.length) { @for (link of gotoMenuResult.nameMatches; track link) { - + } @@ -55,7 +55,7 @@ } @if (gotoMenuResult.crumbMatches.length) { @for (link of gotoMenuResult.crumbMatches; track link) { - + } diff --git a/ui-ngx/src/app/modules/home/menu/goto-menu.component.ts b/ui-ngx/src/app/modules/home/menu/goto-menu.component.ts index 86d2a32832..0b0ba113b1 100644 --- a/ui-ngx/src/app/modules/home/menu/goto-menu.component.ts +++ b/ui-ngx/src/app/modules/home/menu/goto-menu.component.ts @@ -116,10 +116,10 @@ export class GotoMenuComponent implements OnInit, OnDestroy { this.router.navigate([link.path], { queryParams: link.queryParams }).then(); } - private fetchLinks(searchText?: string): Observable { - this.searchText = searchText; + private fetchLinks(searchText: string): Observable { + const query = (searchText ?? '').trim().toLowerCase(); return this.allLinks().pipe( - map((links) => this.filterLinks(links)) + map((links) => this.filterLinks(links, query)) ); } @@ -140,8 +140,7 @@ export class GotoMenuComponent implements OnInit, OnDestroy { return this.allLinksObservable$; } - private filterLinks(links: GotoMenuLink[]): GotoMenuResult { - const query = this.searchText.trim().toLowerCase(); + private filterLinks(links: GotoMenuLink[], query: string): GotoMenuResult { const nameMatches: GotoMenuLink[] = []; let crumbMatches: GotoMenuLink[] = []; for (const link of links) { From 504a8b8ebaff5e72c9d59765fb03f590188ddcf3 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Fri, 27 Nov 2026 16:44:33 +0100 Subject: [PATCH 178/183] Fixed "Navigate to other dashboard" losing the entity when the target dashboard state is empty or missing (#16841) * Fixed "Navigate to other dashboard" losing the entity when the target dashboard state is empty or missing * PR comments fixes --- .../states/default-state-controller.component.ts | 2 +- .../states/entity-state-controller.component.ts | 2 +- .../dashboard-page/states/state-controller.component.ts | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/states/default-state-controller.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/states/default-state-controller.component.ts index a8e96124c3..30cc481643 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/states/default-state-controller.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/states/default-state-controller.component.ts @@ -217,7 +217,7 @@ export class DefaultStateControllerComponent extends StateControllerComponent im if (result && result.length > 1) { result = [ result[result.length - 1] ]; } - return this.normalizeStateObject(result); + return this.normalizeIncomingStateObject(result); } private gotoState(stateId: string, update: boolean, openRightLayout?: boolean) { diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/states/entity-state-controller.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/states/entity-state-controller.component.ts index 03917752a3..d6b13f4855 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/states/entity-state-controller.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/states/entity-state-controller.component.ts @@ -258,7 +258,7 @@ export class EntityStateControllerComponent extends StateControllerComponent imp result = []; } } - return this.normalizeStateObject(result); + return this.normalizeIncomingStateObject(result); } private gotoState(stateId: string, update: boolean, openRightLayout?: boolean, replaceCurrentHistoryUrl?: boolean) { diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/states/state-controller.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/states/state-controller.component.ts index 8f33c61860..5f46b0f528 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/states/state-controller.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/states/state-controller.component.ts @@ -133,6 +133,14 @@ export abstract class StateControllerComponent implements IStateControllerCompon return result; } + protected normalizeIncomingStateObject(stateObject: StateControllerState): StateControllerState { + const result = Array.isArray(stateObject) ? [...stateObject] : []; + if (result.length && (!result[0]?.id || !this.states[result[0].id])) { + result[0] = { ...result[0], id: this.dashboardUtils.getRootStateId(this.states) }; + } + return this.normalizeStateObject(result); + } + protected updateStateParam(newState: string, replaceCurrentHistoryUrl = false) { this.currentState = newState; if (this.syncStateWithQueryParam) { From 054e41dd5fd5bc223764555dd181ee0de03a5fa6 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 30 Nov 2026 08:09:47 +0200 Subject: [PATCH 179/183] Address PR review feedback - AI credits limit increase request rolls back its dedupe key on any failure after it is stored, so a failed attempt no longer blocks retries (PR #16848) - DefaultAiChatServiceTest expects the credit check on createChat (PR #16848) - startNew uses the credit-checking process(action, user) overload and its test verifies it (PR #16848) - Unit tests for owner-scoped alarm subscriptions and TbEntityDataSubCtx.onSameEntities (PR #16848) --- .../controller/NotificationController.java | 42 +++--- .../ai/solution/DefaultAiSolutionService.java | 2 +- .../ai/chat/DefaultAiChatServiceTest.java | 20 +-- .../DefaultAiSolutionServiceTest.java | 6 +- .../subscription/TbAlarmDataSubCtxTest.java | 137 ++++++++++++++++++ .../subscription/TbEntityDataSubCtxTest.java | 66 ++++++++- 6 files changed, 236 insertions(+), 37 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java index e25d41899e..9d2781c3bc 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java @@ -527,29 +527,29 @@ public class NotificationController extends BaseController { if (Objects.equals(aiCreditsRequests.put(requestKey, month), month)) { return; } - NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS) - .stream().findFirst() - .orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found")); - String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request); - Tenant tenant = tenantService.findTenantById(user.getTenantId()); - String limitDescription; - if (pool) { - limitDescription = "all AI credits of this installation's license"; - } else { - long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits(); - limitDescription = String.format("its monthly limit of %,d AI credits", limit); - } - NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder() - .userEmail(user.getEmail()) - .tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString()) - .limitDescription(limitDescription) - .increaseLimitActionLabel(pool ? "Add credits" : "Set new limit") - .increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId()) - .baseUrl(baseUrl) - .build(); try { + NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS) + .stream().findFirst() + .orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found")); + String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request); + Tenant tenant = tenantService.findTenantById(user.getTenantId()); + String limitDescription; + if (pool) { + limitDescription = "all AI credits of this installation's license"; + } else { + long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits(); + limitDescription = String.format("its monthly limit of %,d AI credits", limit); + } + NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder() + .userEmail(user.getEmail()) + .tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString()) + .limitDescription(limitDescription) + .increaseLimitActionLabel(pool ? "Add credits" : "Set new limit") + .increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId()) + .baseUrl(baseUrl) + .build(); notificationCenter.sendSystemNotification(TenantId.SYS_TENANT_ID, sysAdmins.getId(), NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, info); - } catch (RuntimeException e) { + } catch (Exception e) { aiCreditsRequests.remove(requestKey, month); throw e; } 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 6447faf2b4..7e6d1e8414 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 @@ -37,7 +37,7 @@ public class DefaultAiSolutionService implements AiSolutionService { @Override public JsonNode startNew(SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, true); + new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user); } @Override diff --git a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java index f97b8c79bb..7cd8d8f3ba 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java @@ -64,12 +64,12 @@ class DefaultAiChatServiceTest { } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenCreateChatCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenCreateChatCalled() { // GIVEN JsonNode request = createChatRequest("New chat"); UUID chatId = UUID.randomUUID(); JsonNode expectedResponse = TextNode.valueOf(chatId.toString()); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user), eq(true))).willReturn(expectedResponse); // WHEN JsonNode result = service.createChat(request, user); @@ -77,7 +77,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(true).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_CREATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(null, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -94,7 +94,7 @@ class DefaultAiChatServiceTest { service.updateChat(chatId, request, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_UPDATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -113,7 +113,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_LIST.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -132,7 +132,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, JacksonUtil.newObjectNode().put("toolCards", true)), operation.payload())), same(user), same(tokenProvider)); @@ -149,7 +149,7 @@ class DefaultAiChatServiceTest { service.deleteChat(chatId, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_DELETE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -165,7 +165,7 @@ class DefaultAiChatServiceTest { service.stopChat(chatId, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -227,9 +227,9 @@ class DefaultAiChatServiceTest { } @SuppressWarnings({"rawtypes", "unchecked"}) - private TbAiService.TbAiCall captureProcessCall() { + private TbAiService.TbAiCall captureProcessCall(boolean checkCredits) { ArgumentCaptor callCaptor = ArgumentCaptor.forClass(TbAiService.TbAiCall.class); - then(tbAiService).should().process(callCaptor.capture(), same(user), eq(false)); + then(tbAiService).should().process(callCaptor.capture(), same(user), eq(checkCredits)); return callCaptor.getValue(); } 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 73cab7c1dd..444325ab3e 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 @@ -71,10 +71,10 @@ class DefaultAiSolutionServiceTest { } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStartNewCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenStartNewCalled() { // GIVEN JsonNode expectedResponse = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user))).willReturn(expectedResponse); // WHEN JsonNode result = service.startNew(user); @@ -82,7 +82,7 @@ class DefaultAiSolutionServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_START.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java new file mode 100644 index 0000000000..93095a8024 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.subscription; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.id.AlarmId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.query.AlarmData; +import org.thingsboard.server.common.data.query.AlarmDataPageLink; +import org.thingsboard.server.common.data.query.AlarmDataQuery; +import org.thingsboard.server.common.data.query.SingleEntityFilter; +import org.thingsboard.server.dao.alarm.AlarmService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.ws.WebSocketService; +import org.thingsboard.server.service.ws.WebSocketSessionRef; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.AlarmDataUpdate; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.CmdUpdate; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; + +@ExtendWith(MockitoExtension.class) +public class TbAlarmDataSubCtxTest { + + private final String sessionId = "session"; + private final int cmdId = 7; + private final int maxEntitiesPerAlarmSubscription = 100; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); + + @Mock + private WebSocketService webSocketService; + @Mock + private AlarmService alarmService; + @Mock + private WebSocketSessionRef sessionRef; + @Mock + private SecurityUser securityUser; + + private TbAlarmDataSubCtx subCtx; + + @BeforeEach + public void setUp() { + lenient().when(sessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(sessionRef.getSecurityCtx()).thenReturn(securityUser); + lenient().when(securityUser.getTenantId()).thenReturn(tenantId); + subCtx = new TbAlarmDataSubCtx("service", webSocketService, mock(), mock(), mock(), new SubscriptionServiceStatistics(), + alarmService, sessionRef, cmdId, maxEntitiesPerAlarmSubscription, 10); + } + + @Test + public void shouldBeOwnerScoped_onlyWhenQueryHasNoEntityFilter() { + assertThat(subCtx.isOwnerScoped()).isFalse(); + + subCtx.setQuery(query(null, 0)); + assertThat(subCtx.isOwnerScoped()).isTrue(); + + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + assertThat(subCtx.isOwnerScoped()).isFalse(); + } + + @Test + public void shouldSendNothing_whenOwnerScopedRefreshReturnsTheSamePage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + List alarms = List.of(alarmData(), alarmData()); + subCtx.setAlarms(new PageData<>(alarms, 1, 2, false)); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))) + .willReturn(new PageData<>(new ArrayList<>(alarms), 1, 2, false)); + + subCtx.checkAndResetInvocationCounter(); + + then(alarmService).should().findAlarmDataByQuery(eq(tenantId), any(), any(), same(query)); + then(webSocketService).shouldHaveNoInteractions(); + } + + @Test + public void shouldSendTheFreshPage_whenOwnerScopedRefreshReturnsAChangedPage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + subCtx.setAlarms(new PageData<>(List.of(alarmData()), 1, 1, false)); + PageData fresh = new PageData<>(List.of(alarmData(), alarmData()), 1, 2, false); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))).willReturn(fresh); + + subCtx.checkAndResetInvocationCounter(); + + ArgumentCaptor updateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), updateCaptor.capture()); + AlarmDataUpdate update = (AlarmDataUpdate) updateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isSameAs(fresh); + assertThat(update.getUpdate()).isNull(); + assertThat(update.getAllowedEntities()).isEqualTo(maxEntitiesPerAlarmSubscription); + assertThat(subCtx.getAlarms()).isSameAs(fresh); + assertThat(subCtx.getAlarmsMap()).hasSize(2); + } + + @Test + public void shouldNotTouchAlarms_whenCleanupCalledWithoutTimeWindow() { + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + + subCtx.cleanupOldAlarms(); + + then(alarmService).shouldHaveNoInteractions(); + then(webSocketService).shouldHaveNoInteractions(); + } + + private static AlarmDataQuery query(SingleEntityFilter entityFilter, long timeWindow) { + AlarmDataPageLink pageLink = new AlarmDataPageLink(10, 0, null, null, false, false, 0, 0, timeWindow, null, null, null, null); + return new AlarmDataQuery(entityFilter, pageLink, null, null, null, null); + } + + private AlarmData alarmData() { + Alarm alarm = new Alarm(new AlarmId(UUID.randomUUID())); + alarm.setOriginator(deviceId); + return new AlarmData(alarm, deviceId); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java index d104f8d4f4..a7258a31e4 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java @@ -32,10 +32,12 @@ import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.never; @ExtendWith(MockitoExtension.class) public class TbEntityDataSubCtxTest { @@ -57,7 +59,7 @@ public class TbEntityDataSubCtxTest { @BeforeEach public void setUp() { - when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); subCtx = new TbEntityDataSubCtx(serviceId, webSocketService, mock(), mock(), mock(), mock(), webSocketSessionRef, cmdId, maxEntitiesPerDataSubscription); Map subToEntityIdMap = new HashMap<>(); @@ -114,4 +116,64 @@ public class TbEntityDataSubCtxTest { assertThat(entityDataUpdate.getAllowedEntities()).isEqualTo(maxEntitiesPerDataSubscription); } + @Test + public void shouldSendOnlyChangedEntity_whenEntityFieldValueChanged() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + Map changedFields = Map.of("name", new TsValue(2L, "Thermostat 2")); + + subCtx.onSameEntities(Map.of( + deviceId, new EntityData(deviceId, false, false, Map.of(EntityKeyType.ENTITY_FIELD, changedFields), null), + otherId, entityWithFields(otherId, "name", "Pump"))); + + ArgumentCaptor cmdUpdateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), cmdUpdateCaptor.capture()); + EntityDataUpdate update = (EntityDataUpdate) cmdUpdateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isNull(); + assertThat(update.getUpdate()).singleElement().satisfies(entityData -> { + assertThat(entityData.getEntityId()).isEqualTo(deviceId); + assertThat(entityData.getLatest()).isEqualTo(Map.of(EntityKeyType.ENTITY_FIELD, changedFields)); + }); + assertThat(currentFields(deviceId)).isEqualTo(changedFields); + } + + @Test + public void shouldSendNothing_whenEntityFieldValuesUnchanged() { + setCurrentData(entityWithFields(deviceId, "name", "Thermostat")); + + subCtx.onSameEntities(Map.of(deviceId, entityWithFields(deviceId, "name", "Thermostat"))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + } + + @Test + public void shouldSkipEntity_whenFreshEntityFieldsMissingOrEmpty() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + + subCtx.onSameEntities(Map.of(otherId, new EntityData(otherId, false, false, new HashMap<>(Map.of(EntityKeyType.ENTITY_FIELD, Map.of())), null))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + assertThat(currentFields(deviceId)).containsOnlyKeys("name"); + assertThat(currentFields(otherId)).containsOnlyKeys("name"); + } + + private void setCurrentData(EntityData... entities) { + ReflectionTestUtils.setField(subCtx, "data", new PageData<>(List.of(entities), 1, entities.length, false)); + } + + @SuppressWarnings("unchecked") + private Map currentFields(EntityId entityId) { + PageData data = (PageData) ReflectionTestUtils.getField(subCtx, "data"); + return data.getData().stream().filter(entityData -> entityData.getEntityId().equals(entityId)) + .findFirst().orElseThrow().getLatest().get(EntityKeyType.ENTITY_FIELD); + } + + private static EntityData entityWithFields(EntityId entityId, String key, String value) { + Map> latest = new HashMap<>(); + latest.put(EntityKeyType.ENTITY_FIELD, new HashMap<>(Map.of(key, new TsValue(1L, value)))); + return new EntityData(entityId, false, false, latest, null); + } + } From ba7b23e9a1845b9a6c023dbf1055eb1d54eff7e2 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Mon, 30 Nov 2026 14:46:14 +0200 Subject: [PATCH 180/183] Address UI review feedback on the AI chat PR Inline review: legacy ai_solution_creator menu id maps to ai_assistant, quick web link ids use guid(), white labeling and report templates no longer reload over unsaved edits, the solution chat stop state clears when a run ends, the tour skips stops whose target never appears, the hand-over clock runs only while waiting and outside the zone, ai-theme no longer leaks into component stylesheets, SSE heartbeats are ignored, unknown alarm-update actions fall back to "other", the panel margin follows the panel actually being present, and ALARM_RULE reviews get their label. Bundle: the docked panel and the AI Assistant page load lazily; AiModule is split into core, composer and chat modules; the CLI guide moved next to its page. Translations: no sentences assembled in code, plural forms, entity words as keys, wording fixes, unused and stale keys removed, help lists recipient params. Maintainability: one isAiAvailable() rule, one '/' shortcut service, OnPush chat components, shared chat-session helpers, single chat list, shared reload, toast, count and storage helpers, prefixed generic theme classes, Prism skipped where the kit highlighter re-renders code, dead code, CSS and assets removed. License headers restamped and three files curated. --- .../subscription/TbAlarmDataSubCtxTest.java | 4 +- .../subscription/TbEntityDataSubCtxTest.java | 3 +- ...sLimitIncreaseRequestNotificationInfo.java | 5 +- .../python/license-headers/curations.json | 18 + ui-ngx/src/app/core/http/admin.service.ts | 5 - ui-ngx/src/app/core/http/ai-chat.service.ts | 11 +- .../src/app/core/http/custom-menu.service.ts | 4 +- .../app/core/http/user-permissions.service.ts | 8 +- ui-ngx/src/app/core/local-storage/stored.ts | 21 + .../services/ai-assistant-config.service.ts | 17 +- .../services/ai-assistant-panel.service.ts | 37 +- .../src/app/core/services/ai-chats.service.ts | 18 +- .../src/app/core/services/ai-slash.service.ts | 73 ++ ui-ngx/src/app/core/services/menu.models.ts | 5 +- ui-ngx/src/app/core/services/tour.service.ts | 8 +- .../home/components/ai/_ai-icon-button.scss | 40 + .../ai/ai-action-detail.component.html | 8 +- .../ai/ai-action-detail.component.ts | 51 +- .../components/ai/ai-action-detail.models.ts | 28 +- .../components/ai/ai-action-line.component.ts | 7 +- .../home/components/ai/ai-action.models.ts | 100 +- .../ai/ai-approval-card.component.html | 2 +- .../ai/ai-approval-card.component.ts | 11 +- .../ai/ai-artifact-pane.component.ts | 20 +- .../ai/ai-assistant-button.component.ts | 27 +- .../ai/ai-assistant-panel.component.ts | 17 +- .../ai/ai-chat-messages.component.html | 8 +- .../ai/ai-chat-messages.component.scss | 4 - .../ai/ai-chat-messages.component.ts | 41 +- .../home/components/ai/ai-chat-session.ts | 56 ++ .../ai/ai-chat-title.component.scss | 34 +- .../home/components/ai/ai-chat.component.scss | 34 +- .../home/components/ai/ai-chat.component.ts | 86 +- .../home/components/ai/ai-code-block.ts | 21 +- .../home/components/ai/ai-composer.module.ts | 33 + .../home/components/ai/ai-core.module.ts | 44 + .../components/ai/ai-credits-out.component.ts | 13 +- .../ai/ai-credits-popup.component.html | 21 - .../ai/ai-credits-popup.component.scss | 29 - .../ai/ai-credits-popup.component.ts | 26 - .../components/ai/ai-credits.component.html | 93 +- .../components/ai/ai-credits.component.scss | 69 -- .../components/ai/ai-credits.component.ts | 67 +- .../ai/ai-dashboard-generation.service.ts | 11 +- .../components/ai/ai-file-body.component.ts | 17 +- .../components/ai/ai-hand-over.component.html | 6 +- .../components/ai/ai-hand-over.component.ts | 23 +- .../components/ai/ai-limit-out.component.ts | 7 +- .../ai/ai-loading-modal.component.scss | 5 - .../home/components/ai/ai-mark.component.ts | 3 - .../ai/ai-prompt-input.component.html | 2 +- .../ai/ai-prompt-input.component.ts | 39 +- .../components/ai/ai-record-card.component.ts | 17 +- .../components/ai/ai-record-loader.service.ts | 2 +- .../home/components/ai/ai-record.component.ts | 4 +- .../components/ai/ai-records.component.ts | 2 +- .../ai/ai-rename-dialog.component.html | 33 - .../ai/ai-rename-dialog.component.ts | 42 - .../components/ai/ai-run-summary.component.ts | 2 +- .../home/components/ai/ai-tip.directive.ts | 13 +- .../modules/home/components/ai/ai.module.ts | 55 +- .../pane/solution-dashboards.component.ts | 3 +- .../pane/solution-installed.component.scss | 3 - .../pane/solution-installed.component.ts | 3 +- .../solution/pane/solution-json.component.ts | 14 +- .../pane/solution-overview.component.html | 4 +- .../pane/solution-overview.component.ts | 2 + .../ai/solution/pane/solution-pane.scss | 18 - .../ai/solution/solution-chat.component.html | 5 +- .../ai/solution/solution-chat.component.scss | 61 +- .../ai/solution/solution-chat.component.ts | 174 +--- .../alarm-rules/alarm-rules-table-config.ts | 2 +- .../alarm/alarm-comment.component.scss | 2 +- .../components/alarm/alarm-table-config.ts | 4 +- .../calculated-fields-table-config.ts | 3 +- .../dashboard-page.component.ts | 11 +- ...ge-dashboard-layouts-dialog.component.scss | 2 +- .../home/components/home-components.module.ts | 4 +- .../cluster-info-table.component.html | 65 -- .../cluster-info-table.component.scss | 59 -- .../home-page/cluster-info-table.component.ts | 224 ----- .../configured-features.component.html | 71 -- .../configured-features.component.scss | 102 -- .../configured-features.component.ts | 88 -- .../lib/home-page/home-page-widgets.module.ts | 12 - .../license-usage-info.component.html | 80 -- .../license-usage-info.component.scss | 162 ---- .../home-page/license-usage-info.component.ts | 86 -- .../lib/home-page/version-info.component.html | 53 -- .../lib/home-page/version-info.component.scss | 130 --- .../lib/home-page/version-info.component.ts | 39 - .../src/app/modules/home/home.component.html | 4 +- ui-ngx/src/app/modules/home/home.component.ts | 18 +- ui-ngx/src/app/modules/home/home.module.ts | 4 +- .../admin/license-management.component.ts | 2 - .../home/pages/admin/mail-server.component.ts | 5 +- .../pages/admin/mail-templates.component.ts | 5 +- .../two-factor-auth-settings.component.ts | 4 +- .../pages/admin/white-labeling.component.ts | 2 +- .../ai-assistant/ai-assistant-page.module.ts | 27 + .../ai-assistant-routing.module.ts | 6 +- .../ai-assistant/ai-assistant.component.scss | 34 +- .../ai-assistant/ai-assistant.component.ts | 4 +- .../pages/ai-assistant/ai-assistant.module.ts | 12 - .../cli}/ai-cli-guide.component.html | 6 +- .../cli}/ai-cli-guide.component.scss | 36 +- .../cli}/ai-cli-guide.component.ts | 11 +- .../ai-assistant/cli}/ai-cli-term.ts | 2 +- .../ai-assistant/cli}/ai-cli.models.ts | 0 .../pages/ai-assistant/cli/ai-slots.pipe.ts | 48 + .../custom-menu-config.component.ts | 4 +- .../custom-menu-table.component.ts | 8 +- .../translation-map-table.component.ts | 11 +- .../translation-table.component.ts | 8 +- .../dashboard-group-config.factory.ts | 13 +- .../dashboards-table-config.resolver.ts | 20 +- .../home-page/components/_home-table.scss | 9 - .../components/ai-assistant-home.component.ts | 13 +- .../components/ai-start-home.component.ts | 27 +- .../components/alarms-home.component.html | 4 +- .../components/alarms-home.component.ts | 52 +- .../components/dashboards-home.component.html | 2 +- .../components/dashboards-home.component.ts | 13 +- .../devices-activity-home.component.ts | 3 +- .../components/devices-home.component.html | 2 +- .../components/devices-home.component.ts | 31 +- .../get-started-home.component.html | 2 +- .../get-started-home.component.scss | 10 - .../components/get-started-home.component.ts | 17 +- .../get-started-sys-admin-home.component.html | 2 +- .../get-started-sys-admin-home.component.scss | 8 - .../get-started-sys-admin-home.component.ts | 29 +- .../components/home-card.component.ts | 17 +- .../home-page/components/home-toast.scss | 1 - .../install-items-home.component.html | 2 +- .../install-items-home.component.ts | 21 +- .../components/iot-hub-home.component.ts | 7 +- .../components/license-home.component.html | 2 +- .../components/license-home.component.scss | 9 - .../components/license-home.component.ts | 13 +- .../notifications-home.component.ts | 13 +- .../product-release-home.component.ts | 17 +- .../quick-link-dialog.component.scss | 1 - .../quick-links-home.component.html | 2 +- .../quick-links-home.component.scss | 1 - .../components/quick-links-home.component.ts | 10 +- .../components/status-line-home.component.ts | 31 +- .../system-status-home.component.ts | 6 +- .../waiting-ai-chats-home.component.ts | 13 +- .../pages/home-page/home-count.service.ts | 60 ++ .../home/pages/home-page/home-list.models.ts | 17 +- .../pages/home-page/home-page.component.scss | 5 +- .../pages/home-page/home-page.component.ts | 5 +- .../home/pages/home-page/home-page.module.ts | 9 +- .../pages/home-page/quick-links.models.ts | 3 +- ...obile-qr-code-widget-settings.component.ts | 5 +- .../notification-settings.component.ts | 5 +- .../home/pages/profile/profile.component.ts | 5 +- .../report-template-page.component.ts | 23 +- .../template/report-template.module.ts | 4 +- .../report-templates-table-config.resolver.ts | 19 +- .../scada-symbol/scada-symbol.component.ts | 17 +- .../home/pages/security/security.component.ts | 6 +- .../pages/widget/widget-editor.component.ts | 16 +- .../pages/widget/widget-library.module.ts | 7 +- .../widget-types-table-config.resolver.ts | 16 +- .../widgets-bundle-widgets.component.ts | 16 +- .../widgets-bundles-table-config.resolver.ts | 3 +- .../app/modules/tour/tour-launcher.service.ts | 6 +- .../tour/welcome-invitation.component.html | 2 +- .../tour/welcome-invitation.component.scss | 15 - .../shared/components/markdown.component.ts | 11 +- ...ssword-requirements-tooltip.component.html | 3 +- ...password-requirements-tooltip.component.ts | 3 +- .../app/shared/models/custom-menu.models.ts | 27 + ui-ngx/src/app/shared/models/device.models.ts | 9 +- .../app/shared/models/notification.models.ts | 4 +- .../src/app/shared/models/password.models.ts | 3 +- .../src/app/shared/models/settings.models.ts | 7 - .../app/shared/models/user-settings.models.ts | 1 - .../ai_credits_limit_increase_request.md | 6 +- .../assets/locale/locale.constant-ar_AE.json | 95 +- .../assets/locale/locale.constant-ca_ES.json | 95 +- .../assets/locale/locale.constant-cs_CZ.json | 10 +- .../assets/locale/locale.constant-da_DK.json | 95 +- .../assets/locale/locale.constant-de_DE.json | 93 +- .../assets/locale/locale.constant-el_GR.json | 95 +- .../assets/locale/locale.constant-en_US.json | 277 +++--- .../assets/locale/locale.constant-es_ES.json | 93 +- .../assets/locale/locale.constant-fa_IR.json | 10 +- .../assets/locale/locale.constant-fr_FR.json | 93 +- .../assets/locale/locale.constant-hi_IN.json | 95 +- .../assets/locale/locale.constant-it_IT.json | 93 +- .../assets/locale/locale.constant-ja_JP.json | 93 +- .../assets/locale/locale.constant-ka_GE.json | 10 +- .../assets/locale/locale.constant-ko_KR.json | 95 +- .../assets/locale/locale.constant-lt_LT.json | 95 +- .../assets/locale/locale.constant-lv_LV.json | 10 +- .../assets/locale/locale.constant-nl_BE.json | 95 +- .../assets/locale/locale.constant-nl_NL.json | 93 +- .../assets/locale/locale.constant-no_NO.json | 95 +- .../assets/locale/locale.constant-pl_PL.json | 95 +- .../assets/locale/locale.constant-pt_BR.json | 93 +- .../assets/locale/locale.constant-ro_RO.json | 10 +- .../assets/locale/locale.constant-sl_SI.json | 95 +- .../assets/locale/locale.constant-tr_TR.json | 95 +- .../assets/locale/locale.constant-uk_UA.json | 93 +- .../assets/locale/locale.constant-zh_CN.json | 95 +- .../assets/locale/locale.constant-zh_TW.json | 97 +- .../assets/solution-creator/iot-assistant.svg | 3 - .../src/assets/solution-creator/success.svg | 4 - ui-ngx/src/scss/roboto.scss | 4 + ui-ngx/src/theme/_app-theme-palette.scss | 23 + ui-ngx/src/theme/ai-theme.scss | 874 +++++++----------- ui-ngx/src/theme/app-theme.scss | 21 +- 215 files changed, 1664 insertions(+), 5686 deletions(-) create mode 100644 ui-ngx/src/app/core/local-storage/stored.ts create mode 100644 ui-ngx/src/app/core/services/ai-slash.service.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts create mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss delete mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-page.module.ts rename ui-ngx/src/app/modules/home/{components/ai => pages/ai-assistant/cli}/ai-cli-guide.component.html (94%) rename ui-ngx/src/app/modules/home/{components/ai => pages/ai-assistant/cli}/ai-cli-guide.component.scss (97%) rename ui-ngx/src/app/modules/home/{components/ai => pages/ai-assistant/cli}/ai-cli-guide.component.ts (96%) rename ui-ngx/src/app/modules/home/{components/ai => pages/ai-assistant/cli}/ai-cli-term.ts (99%) rename ui-ngx/src/app/modules/home/{components/ai => pages/ai-assistant/cli}/ai-cli.models.ts (100%) create mode 100644 ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts create mode 100644 ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts delete mode 100644 ui-ngx/src/assets/solution-creator/iot-assistant.svg delete mode 100644 ui-ngx/src/assets/solution-creator/success.svg create mode 100644 ui-ngx/src/theme/_app-theme-palette.scss diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java index 93095a8024..a27ad861f8 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java @@ -1,5 +1,5 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.subscription; import org.junit.jupiter.api.BeforeEach; diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java index a7258a31e4..8a50384edc 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.subscription; import org.apache.commons.lang3.RandomStringUtils; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java index ca5bed0a32..dee1b1378f 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java @@ -1,5 +1,6 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.data.notification.info; import lombok.AllArgsConstructor; diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 18e0ec560f..638962740c 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -421,6 +421,12 @@ "reason": "PE custom menu model interface introduced in 2eb81a2baa9 alongside CustomMenuConfig. The candidate CE DeviceConfiguration.java matches only on Jackson polymorphism annotations, not on the menu model. Reviewed candidate at 317a75614137ab5ddd1aecef1abd4c2fcdcb8710 (blob 6fe689d17c0).", "contentHash": "sha256:da19b1162913a636119fcc953d6366b990d24a6fda8df540497653bb317407b0" }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java", + "header": "ce-modified", + "reason": "Copied from the CE EntitiesLimitIncreaseRequestNotificationInfo and adapted: entityType replaced by tenantName and limitDescription, same structure and template data map. Reviewed against CE common/data/src/main/java/org/thingsboard/server/common/data/notification/info/EntitiesLimitIncreaseRequestNotificationInfo.java at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 9595b4414fd87b3740479c730c8c39928d003e7b).", + "contentHash": "sha256:362d939f065b94a46db4258c87598278b4f4db7b6dcf82a0a57dd762a8f09635" + }, { "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/IntegrationLifecycleEventNotificationInfo.java", "header": "busl", @@ -1195,6 +1201,12 @@ "reason": "Configuration holder for the PE customer-attribute rule node. Reviewed property defaults configure this PE node; common rule-node configuration/clone patterns do not establish derivation from the CE entity-data node. Reviewed candidate rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/metadata/TbGetEntityDataNodeConfiguration.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob f68fdf321b69b24e3e15bd2a311e2ccfa86ff890).", "contentHash": "sha256:0b91a00b698884c6654781d43c0debb2e61dcfcb9898811e27dc13baafde2bb0" }, + { + "path": "ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss", + "header": "busl", + "reason": "New AI approval card stylesheet holding only a one-line ':host { display: block; }' rule; it matches CE socialshare-panel.component.scss only because that rule is generic boilerplate, not because anything was copied from it. Reviewed against CE ui-ngx/src/app/shared/components/socialshare-panel.component.scss at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 75f4e82b7187d38898ab858dc6a20be6058e9e20).", + "contentHash": "sha256:49fd378740956adca949bca4777b25410d4d9c562716602678360a3aa7f82a91" + }, { "path": "ui-ngx/src/app/modules/home/components/converter/converter-autocomplete.component.scss", "header": "busl", @@ -1393,6 +1405,12 @@ "reason": "New PE file implementing a PE feature. It was written by adapting CE ui-ngx/src/app/modules/home/pages/dashboard/make-dashboard-public-dialog.component.ts, which PE still carries at its own path, so this is not a CE file with PE modifications. Adaptation from CE does not make it CE-derived. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.", "contentHash": "sha256:07f295f637db24d600798215d33391f4e966954899f644a41b9735f5ed5392db" }, + { + "path": "ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html", + "header": "ce-modified", + "reason": "Renamed from CE home-links.component.html; it keeps the CE embedded tb-dashboard-page for an assigned home dashboard and replaces the links grid with the new Home pages. Reviewed against CE ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 3f7184d1828f217480f5e12486f1ff0704d2f7c4).", + "contentHash": "sha256:ab7b00962003c516bce4af3dabc068c37b0d9ee773e960f8607b6a155514f76b" + }, { "path": "ui-ngx/src/app/modules/home/pages/iframe/iframe-view.module.ts", "header": "busl", diff --git a/ui-ngx/src/app/core/http/admin.service.ts b/ui-ngx/src/app/core/http/admin.service.ts index 8f76ee61c7..77591e5d29 100644 --- a/ui-ngx/src/app/core/http/admin.service.ts +++ b/ui-ngx/src/app/core/http/admin.service.ts @@ -10,7 +10,6 @@ import { AutoCommitSettings, FeaturesInfo, JwtSettings, - LicenseUsageInfo, MailConfigTemplate, MailServerSettings, RepositorySettings, @@ -128,10 +127,6 @@ export class AdminService { return this.http.get('/api/admin/featuresInfo', defaultHttpOptionsFromConfig(config)); } - public getLicenseUsageInfo(config?: RequestConfig): Observable { - return this.http.get('/api/admin/licenseUsageInfo', defaultHttpOptionsFromConfig(config)); - } - public getSubscriptionInfo(config?: RequestConfig): Observable { return this.http.get('/api/admin/subscriptionInfo', defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/ai-chat.service.ts b/ui-ngx/src/app/core/http/ai-chat.service.ts index 40688aa479..645ab4a114 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -62,14 +62,14 @@ export class AiChatService { return this.streamEvents(`/api/ai/chats/${chatId}/messages`, request, config); } - /** - * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the - * live ones. Completes with no events when nothing is running. - */ public stopChat(chatId: string, config?: RequestConfig): Observable { return this.http.post(`/api/ai/chats/${chatId}/stop`, null, defaultHttpOptionsFromConfig(config)); } + /** + * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the + * live ones. Completes with no events when nothing is running. + */ public resumeChat(chatId: string, config?: RequestConfig): Observable { return this.streamEvents(`/api/ai/chats/${chatId}/resume`, null, config); } @@ -119,6 +119,9 @@ export class AiChatService { const result: Partial = {}; const lines = input.trim().split('\n'); + if (lines.every(line => !line.trim() || line.trim().startsWith(':'))) { + return null; + } for (const line of lines) { const trimmedLine = line.trim(); diff --git a/ui-ngx/src/app/core/http/custom-menu.service.ts b/ui-ngx/src/app/core/http/custom-menu.service.ts index 7c896934e2..92ad715dd6 100644 --- a/ui-ngx/src/app/core/http/custom-menu.service.ts +++ b/ui-ngx/src/app/core/http/custom-menu.service.ts @@ -7,7 +7,8 @@ import { CustomMenu, CustomMenuConfig, CustomMenuDeleteResult, - CustomMenuInfo + CustomMenuInfo, + withCurrentMenuIds } from '@shared/models/custom-menu.models'; import { mergeMap, Observable, of, Subject } from 'rxjs'; import { map, tap } from 'rxjs/operators'; @@ -38,6 +39,7 @@ export class CustomMenuService { public loadCustomMenu(notify = false): Observable { return this.http.get('/api/customMenu') .pipe( + map(customMenuConfig => withCurrentMenuIds(customMenuConfig)), tap((customMenuConfig) => { this.customMenuConfig = customMenuConfig; if (notify) { diff --git a/ui-ngx/src/app/core/http/user-permissions.service.ts b/ui-ngx/src/app/core/http/user-permissions.service.ts index 71f952154d..d31ddfe2b4 100644 --- a/ui-ngx/src/app/core/http/user-permissions.service.ts +++ b/ui-ngx/src/app/core/http/user-permissions.service.ts @@ -20,6 +20,7 @@ import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-uti import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; @Injectable({ providedIn: 'root' @@ -126,11 +127,16 @@ export class UserPermissionsService { return getCurrentAuthState(this.store).aiEnabled; } + public isAiAvailable(operation: Operation = Operation.ALL): boolean { + const authState = getCurrentAuthState(this.store); + return !!authState?.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN + && this.hasGenericPermission(Resource.AI, operation); + } + private isResourceAllowed(resource: Resource): boolean { return !this.allowedResources || this.allowedResources.indexOf(resource) > -1; } - public hasGenericPermissionByEntityGroupType(operation: Operation, groupType: EntityType): boolean { if (!groupType) { return false; diff --git a/ui-ngx/src/app/core/local-storage/stored.ts b/ui-ngx/src/app/core/local-storage/stored.ts new file mode 100644 index 0000000000..8638c04710 --- /dev/null +++ b/ui-ngx/src/app/core/local-storage/stored.ts @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +export function readStored(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} + +export function writeStored(key: string, value: string | null): void { + try { + if (value === null) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, value); + } + } catch { + return; + } +} diff --git a/ui-ngx/src/app/core/services/ai-assistant-config.service.ts b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts index b1474c28bb..6f6f32d6f0 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-config.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts @@ -1,26 +1,31 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { inject, Injectable } from '@angular/core'; -import { Store } from '@ngrx/store'; import { TranslateService } from '@ngx-translate/core'; -import { AppState } from '@core/core.state'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; import { EntityId } from '@shared/models/id/entity-id'; +import { HeaderActionDescriptor } from '@home/models/entity/entities-table-config.models'; @Injectable({ providedIn: 'root' }) export class AiAssistantConfigService { - private store = inject>(Store); private userPermissionsService = inject(UserPermissionsService); private translate = inject(TranslateService); + configureAction(onAction: ($event: MouseEvent) => void): HeaderActionDescriptor[] { + return this.userPermissionsService.isAiAvailable() ? [{ + name: this.translate.instant('ai-assistant.configure-with-ai'), + icon: 'mdi:creation', + isEnabled: () => true, + onAction + }] : []; + } + tableConfig(listView: AiAssistantViewType, entityView?: AiAssistantViewType, listEntityId?: EntityId): AiAssistantPanelConfig | null { - if (!getCurrentAuthState(this.store).aiEnabled || !this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { + if (!this.userPermissionsService.isAiAvailable()) { return null; } return { diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index e45637b55a..c742ca7fb6 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: BUSL-1.1 import { computed, DestroyRef, effect, inject, Injectable, OnDestroy, signal } from '@angular/core'; import { defer, Observable, Subject } from 'rxjs'; -import { distinctUntilChanged, filter, finalize, map } from 'rxjs/operators'; +import { buffer, debounceTime, distinctUntilChanged, filter, finalize, map } from 'rxjs/operators'; import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, ChatInfo, AiPromptMessage } from '@shared/models/ai-chat.models'; +import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, AiPromptMessage } from '@shared/models/ai-chat.models'; import { EntityId } from '@shared/models/id/entity-id'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { LocalStorageService } from '@core/local-storage/local-storage.service'; @@ -28,6 +28,7 @@ export class AiAssistantPanelService implements OnDestroy { private static readonly WITHOUT_PANEL = ['/home', '/ai-assistant']; private static readonly OPEN_KEY = 'tb-ai-panel-open'; + private static readonly RELOAD_DEBOUNCE_MS = 1000; private static readonly CHATS_KEY = 'tb-ai-panel-chats'; private _open = signal(AiAssistantPanelService.readSession(AiAssistantPanelService.OPEN_KEY) === 'true'); @@ -55,8 +56,6 @@ export class AiAssistantPanelService implements OnDestroy { private _sentClientContextByChat = new Map(); - private _chats = signal(null); - readonly chats = this._chats.asReadonly(); private _lastChatIdByContext = AiAssistantPanelService.readChats(); @@ -148,7 +147,7 @@ export class AiAssistantPanelService implements OnDestroy { }); private resetUserState(): void { - this._chats.set(null); + this._open.set(false); this._sentClientContextByChat.clear(); this._lastChatIdByContext.clear(); this._carried = null; @@ -158,6 +157,10 @@ export class AiAssistantPanelService implements OnDestroy { private _updatedData$ = new Subject>(); readonly updatedData$ = this._updatedData$.asObservable(); + readonly updatedDataBatches$: Observable> = this.updatedData$.pipe( + buffer(this.updatedData$.pipe(debounceTime(AiAssistantPanelService.RELOAD_DEBOUNCE_MS))), + map(batches => batches.flat()) + ); private _teardownTimer: NodeJS.Timeout; @@ -216,20 +219,7 @@ export class AiAssistantPanelService implements OnDestroy { this._open.update(open => !open); } - setChats(chats: ChatInfo[]): void { - this._chats.set(chats); - } - - addChat(chat: ChatInfo): void { - this._chats.update(list => [chat, ...(list ?? [])]); - } - - updateChatTitle(chatId: string, title: string): void { - this._chats.update(list => list?.map(c => c.id === chatId ? {...c, title} : c) ?? null); - } - - removeChat(chatId: string): void { - this._chats.update(list => list?.filter(c => c.id !== chatId) ?? null); + forgetChat(chatId: string): void { this._sentClientContextByChat.delete(chatId); for (const [key, id] of this._lastChatIdByContext) { if (id === chatId) { @@ -239,10 +229,6 @@ export class AiAssistantPanelService implements OnDestroy { this.storeChats(); } - updateChatAutoApprove(chatId: string, autoApprove: boolean): void { - this._chats.update(list => list?.map(c => c.id === chatId ? {...c, autoApprove} : c) ?? null); - } - takeStoredAutoApproveChats(): string[] { const key = `${AiAssistantPanelService.AUTO_APPROVE_STORAGE_KEY}_${this._autoApproveUserId ?? 'anonymous'}`; try { @@ -442,6 +428,10 @@ export class AiAssistantPanelService implements OnDestroy { private _customizationSaved$ = new Subject(); readonly customizationSaved$ = this._customizationSaved$.asObservable(); + customizationReload$(kind: AiCustomizationSaved['kind'], clean: () => boolean = () => true): Observable { + return this.customizationSaved$.pipe(filter(event => event.kind === kind && clean())); + } + emitCustomizationSaved(event: AiCustomizationSaved): void { this._customizationSaved$.next(event); } @@ -470,7 +460,6 @@ export class AiAssistantPanelService implements OnDestroy { this._clientContext.set(null); this._viewName.set(null); this._sentClientContextByChat.clear(); - this._chats.set(null); this._teardownTimer = setTimeout(() => { this._config.set(null); }); diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts index 27efcb2e22..d35116c93e 100644 --- a/ui-ngx/src/app/core/services/ai-chats.service.ts +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -6,10 +6,8 @@ import { distinctUntilChanged, filter, map, skip, switchMap, tap } from 'rxjs/op import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState, selectAuthUser } from '@core/auth/auth.selectors'; +import { selectAuthUser } from '@core/auth/auth.selectors'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Authority } from '@shared/models/authority.enum'; -import { Operation, Resource } from '@shared/models/security.models'; import { TranslateService } from '@ngx-translate/core'; import { AiChatService } from '@core/http/ai-chat.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; @@ -86,9 +84,7 @@ export class AiChatsService { } private aiAvailable(): boolean { - const authState = getCurrentAuthState(this.store); - return !!authState?.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN - && this.userPermissions.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissions.isAiAvailable(); } watchStatus(): void { @@ -244,7 +240,6 @@ export class AiChatsService { next: chats => { this._chats.set(chats); this._loaded.set(true); - this.panelService.setChats(chats); this.moveStoredAutoApprove(chats); }, error: () => this._loaded.set(true) @@ -262,9 +257,6 @@ export class AiChatsService { map(id => ({id, title, createdTime: Date.now(), autoApprove} as ChatInfo)), tap(chat => { this._chats.update(list => [chat, ...list]); - if (this.panelService.chats() !== null) { - this.panelService.addChat(chat); - } }) ); } @@ -293,7 +285,6 @@ export class AiChatsService { private applyAutoApprove(chatId: string, autoApprove: boolean): void { this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, autoApprove} : chat)); - this.panelService.updateChatAutoApprove(chatId, autoApprove); } private moveStoredAutoApprove(chats: ChatInfo[]): void { @@ -310,14 +301,13 @@ export class AiChatsService { setTitle(chatId: string, title: string): void { this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat)); - this.panelService.updateChatTitle(chatId, title); } discard(chatId: string): Observable { return this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).pipe( tap(() => { this._chats.update(list => list.filter(c => c.id !== chatId)); - this.panelService.removeChat(chatId); + this.panelService.forgetChat(chatId); }) ); } @@ -334,7 +324,7 @@ export class AiChatsService { ? this.aiChat.deleteChat(chat.id, {ignoreLoading: true, ignoreErrors: true}).pipe( tap(() => { this._chats.update(list => list.filter(c => c.id !== chat.id)); - this.panelService.removeChat(chat.id); + this.panelService.forgetChat(chat.id); }), map(() => true) ) diff --git a/ui-ngx/src/app/core/services/ai-slash.service.ts b/ui-ngx/src/app/core/services/ai-slash.service.ts new file mode 100644 index 0000000000..1cd795dcf0 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-slash.service.ts @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable, NgZone } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; + +export interface AiSlashComposer { + field(): HTMLTextAreaElement | undefined; + focusEnd(): void; +} + +export interface AiSlashOpener { + canOpen(): boolean; + open(): void; +} + +@Injectable({ + providedIn: 'root' +}) +export class AiSlashService { + + private zone = inject(NgZone); + private dialog = inject(MatDialog); + private composers = new Set(); + private opener: AiSlashOpener | null = null; + private listening = false; + + addComposer(composer: AiSlashComposer): () => void { + this.listen(); + this.composers.add(composer); + return () => this.composers.delete(composer); + } + + setOpener(opener: AiSlashOpener): () => void { + this.listen(); + this.opener = opener; + return () => { + if (this.opener === opener) { + this.opener = null; + } + }; + } + + private listen(): void { + if (this.listening) { + return; + } + this.listening = true; + this.zone.runOutsideAngular(() => document.addEventListener('keydown', event => this.onKeydown(event))); + } + + private onKeydown(event: KeyboardEvent): void { + if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented || this.dialog.openDialogs.length + || (event.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable]')) { + return; + } + const visible = Array.from(this.composers) + .filter(composer => { + const field = composer.field(); + return !!field?.offsetParent && !field.closest('tb-ai-assistant-panel:not(.open)'); + }) + .sort((a, b) => a.field().compareDocumentPosition(b.field()) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); + const last = visible[visible.length - 1]; + if (last) { + event.preventDefault(); + this.zone.run(() => last.focusEnd()); + return; + } + if (this.opener?.canOpen()) { + event.preventDefault(); + this.zone.run(() => this.opener.open()); + } + } +} diff --git a/ui-ngx/src/app/core/services/menu.models.ts b/ui-ngx/src/app/core/services/menu.models.ts index 38a364e0b8..a72e72d026 100644 --- a/ui-ngx/src/app/core/services/menu.models.ts +++ b/ui-ngx/src/app/core/services/menu.models.ts @@ -1582,10 +1582,7 @@ const menuFilters = new Map([ userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL) ], [ - MenuId.ai_assistant, (authState, userPermissionsService) => - authState.aiEnabled && - authState.authUser.authority === Authority.TENANT_ADMIN && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) + MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable() ], [ MenuId.device_all, (_authState, userPermissionsService) => diff --git a/ui-ngx/src/app/core/services/tour.service.ts b/ui-ngx/src/app/core/services/tour.service.ts index 05a338d6ae..5e6b27768a 100644 --- a/ui-ngx/src/app/core/services/tour.service.ts +++ b/ui-ngx/src/app/core/services/tour.service.ts @@ -4,10 +4,8 @@ import { createNgModule, inject, Injectable, Injector, signal, untracked } from import { Store } from '@ngrx/store'; import { MatDialog } from '@angular/material/dialog'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState, getCurrentUserSettings } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; +import { getCurrentUserSettings } from '@core/auth/auth.selectors'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { AiTourStep } from '@shared/models/user-settings.models'; import { AiChatsService } from '@core/services/ai-chats.service'; @@ -34,9 +32,7 @@ export class TourService { private offered = false; aiAvailable(): boolean { - const authState = getCurrentAuthState(this.store); - return !!authState?.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN - && this.userPermissions.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissions.isAiAvailable(); } offerWelcome(): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss new file mode 100644 index 0000000000..894eeaad97 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@mixin ai-icon-button($color: var(--tb-ink-54), $icon: 19px, $tap: true, $relative: true) { + @if $relative { + position: relative; + } + flex: none; + width: 32px; + height: 32px; + @if $tap { + min-width: var(--chat-tap); + min-height: var(--chat-tap); + } + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: $color; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: $icon; + width: $icon; + height: $icon; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html index dd8eeac316..d08107aa5b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -123,7 +123,7 @@ }
      @for (row of block.rows; track $index) { -
    • {{ row }}
    • +
    • {{ rowText(row) }}
    • }
    } @@ -134,7 +134,7 @@ @if (block.title) {
    {{ ('ai-assistant.action.' + block.title) | translate }}
    } -
    {{ block.text }}
    +
    {{ block.text }}
    } @case ('links') { } @else if (json()) { - + (applied)="applyJson($event)" (discarded)="onJsonDiscarded()"> } @else { @switch (currentView()) { @case ('overview') { diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss index 2aa803a1e9..f501c1bbf6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +@use '../ai-icon-button' as *; :host { position: relative; width: 100%; @@ -57,35 +58,7 @@ tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions { } .sol-ib { - flex: none; - width: 32px; - height: 32px; - padding: 0; - border: 0; - border-radius: 8px; - background: none; - color: var(--tb-ink-54); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: background-color .15s ease, color .15s ease; - - &:hover { - background: rgba(0, 0, 0, 0.06); - color: var(--tb-ink); - } - - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 1px; - } - - .mat-icon { - font-size: 20px; - width: 20px; - height: 20px; - } + @include ai-icon-button($icon: 20px, $tap: false, $relative: false); } .sol-toast { @@ -519,16 +492,13 @@ tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions { .art-pane-foot { .warn { --mat-button-text-label-text-color: var(--tb-crit); - --mdc-text-button-label-text-color: var(--tb-crit); } .sol-foot-stroked.mat-mdc-outlined-button { padding: 0 15px; background: var(--tb-surface); --mat-button-outlined-label-text-color: var(--tb-ink-76); - --mdc-outlined-button-label-text-color: var(--tb-ink-76); --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.1); - --mdc-outlined-button-outline-color: rgba(0, 0, 0, 0.1); } } @@ -547,33 +517,6 @@ tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions { flex: 1; } -.sol-result { - margin: auto; - padding: 32px 24px; - display: flex; - flex-direction: column; - align-items: center; - text-align: center; - gap: 8px; - color: var(--tb-ink); -} - -.sol-result-pic { - color: var(--tb-primary-500); - margin-bottom: 8px; -} - -.sol-result-title { - font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); -} - -.sol-result-sub { - max-width: 420px; - font-size: var(--chat-text); - line-height: var(--chat-text-lh); - color: var(--tb-ink-76); -} - .sol-failure { display: flex; align-items: flex-start; diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts index 0a19746824..4291e66394 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -5,12 +5,12 @@ import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; import { AiNotice } from '@shared/models/ai-chat.models'; import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component'; import { + ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, - viewChild, EventEmitter, HostListener, inject, @@ -19,6 +19,7 @@ import { Output, signal, untracked, + viewChild, ViewChild } from '@angular/core'; import { @@ -79,6 +80,8 @@ import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solutio import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; import { AiSpinKind } from '@home/components/ai/ai-action.models'; import { aiAnswersOf, aiAnswersText } from '@home/components/ai/ai-question.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session'; import { EntityId } from '@shared/models/id/entity-id'; export type SolutionView = 'overview' | 'dashboards' | 'solution'; @@ -92,6 +95,7 @@ function formatCredits(credits: number): string { } @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-solution-chat', templateUrl: './solution-chat.component.html', styleUrls: ['./solution-chat.component.scss'], @@ -100,7 +104,6 @@ function formatCredits(credits: number): string { export class SolutionChatComponent extends PageComponent implements OnInit, OnDestroy { private static readonly NARROW_WIDTH = 1100; - private static readonly END_IN_VIEW = 160; private static readonly CREDITS_PIN_MS = 1500; private static readonly CONNECTIVITY_GUIDE = 'https://thingsboard.io/docs/getting-started-guides/connectivity/'; @@ -209,18 +212,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe }); onLogScroll(area: HTMLElement): void { - const scrolled = area.scrollTop > 0; - if (scrolled !== this.logScrolled()) { - this.logScrolled.set(scrolled); - } - const atEnd = area.scrollHeight - area.scrollTop - area.clientHeight < SolutionChatComponent.END_IN_VIEW; - if (atEnd !== this.atEnd()) { - this.atEnd.set(atEnd); - } - if (atEnd) { - this.newTurns.set(0); - this.seenTurns = this.viewMessages().length; - } + aiTrackLogScroll(area, {scrolled: this.logScrolled, atEnd: this.atEnd, newTurns: this.newTurns}, () => this.seenTurns = this.viewMessages().length); } goToEnd(area: HTMLElement): void { @@ -249,8 +241,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe json = signal(false); - jsonEditing = signal(false); - opening = signal(false); jsonWrap = signal(SolutionChatComponent.stored('tbAiFileWrap') === 'true'); @@ -265,8 +255,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private clipboardService = inject(ClipboardService); - jsonDraftId = signal(''); - toggleJsonWrap(): void { this.jsonWrap.update(wrap => !wrap); SolutionChatComponent.store('tbAiFileWrap', String(this.jsonWrap())); @@ -307,19 +295,11 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } private static stored(key: string): string | null { - try { - return localStorage.getItem(key); - } catch { - return null; - } + return readStored(key); } private static store(key: string, value: string): void { - try { - localStorage.setItem(key, value); - } catch { - return; - } + writeStored(key, value); } uninstalledAt = signal(null); @@ -332,6 +312,11 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private messageSteps: SolutionStep[] = []; stopping = signal(false); + private readonly stopEnded = effect(() => { + if (!this.loading() && !this.isGenerating()) { + untracked(() => this.stopping.set(false)); + } + }); notice = signal(null); @@ -637,69 +622,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe : this.pendingQuestions().length ? 'solution-creator.type-the-answer' : this.creatorStep() === 'result' ? 'solution-creator.ask-about-solution' : 'solution-creator.say-what-to-change'); - activeStepIndex = computed(() => { - if (!this.creatorStep()) { - return -1; - } - if (this.creatorStep() === 'result') { - return 2; - } - if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - return 1; - } - return 0; - }); - - stepperLabels: string[] = [ - 'solution-creator.step-architecture-design', - 'solution-creator.step-dashboard-design', - 'solution-creator.step-solution-installation', - ]; - - stepStatuses = signal>(['pending', 'pending', 'pending']); - - goToStep(index: number): void { - if (this.stepStatuses()[index] !== 'ready') { - return; - } - this.forceScroll = true; - if (index === 0) { - this.creatorStep.set('chat'); - this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); - this.updatedCurrentMsg(); - } else if (index === 1) { - this.creatorStep.set('chat'); - this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); - this.updatedCurrentMsg(); - } else if (index === 2) { - this.creatorStep.set('result'); - } - } - - private updateStepStatuses(): void { - const active = this.activeStepIndex(); - const statuses: Array<'ready' | 'active' | 'pending'> = [0, 1, 2].map(i => { - if (i === active) { - return 'active'; - } - if (!this.solutionInfo) { - return 'pending'; - } - if (i === 0 && this.solutionInfo.states?.[SolutionStep.INITIAL_CONFIGURATION]?.status === SolutionStepStatus.READY) { - return 'ready'; - } - if (i === 1 && this.solutionInfo.states?.[SolutionStep.DASHBOARDS_CONFIGURATION]?.status === SolutionStepStatus.READY) { - return 'ready'; - } - if (i === 2 && this.solutionInfo.metadata?.built) { - return 'ready'; - } - return 'pending'; - }); - this.stepStatuses.set(statuses); - } - - solutionExamples: Array<{ key: string; labelKey: string; icon: string; message: string }> = [ { key: 'coffeeMonitor', @@ -759,10 +681,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe ]; SolutionStep = SolutionStep; - solutionDescriptor: SolutionDescriptor; - dashboardsOverview: DashboardsOverview[]; - solutionName: string; - private solutionId: string; private _solutionInfo: SolutionCreatorInfo; @@ -779,7 +697,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.installed.set(!!value?.metadata?.installed); const main = value?.metadata?.installResult?.mainDashboardId; this.mainDashboard.set(value?.metadata?.installed && main ? [main] : []); - this.updateStepStatuses(); } private messages$ = toObservable(this.messages); private forceScroll = false; @@ -799,10 +716,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe private authService: AuthService) { super(); - toObservable(this.activeStepIndex).pipe( - takeUntilDestroyed(), - ).subscribe(() => this.updateStepStatuses()); - this.messages$.pipe( takeUntilDestroyed(), ).subscribe(value => { @@ -1194,7 +1107,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe : seconds < 90 ? this.translate.instant('solution-creator.pane.estimate-solution') : this.translate.instant('solution-creator.pane.about-minutes', {count: Math.round(seconds / 60)}); - return credits > 0 ? time + ' · ' + this.translate.instant('solution-creator.pane.credits', {credits: formatCredits(credits)}) : time; + return credits > 0 ? time + ' · ' + this.translate.instant('solution-creator.pane.credits', {credits: formatCredits(credits), count: credits}) : time; } answerQuestions(answers: AiQuestionAnswer[]): void { @@ -1211,35 +1124,27 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe onRate(event: AnswerRatingEvent): void { const target = this.answerAt(event.index); - if (!target) { - return; + if (target) { + aiRateAnswer(event, target.answer.rating, this.answerFeedback(event.index, target)); } - const before = target.answer.rating; - this.patchAnswer(event.index, {rating: event.rating === 'NONE' ? undefined : event.rating}); - this.aiSolutions.sendFeedback(this.solutionId, target.step, {answer: target.answer.content, rating: event.rating}).subscribe({ - error: () => { - this.patchAnswer(event.index, {rating: before}); - this.showErrorMessage(this.translate.instant('ai-assistant.feedback.failed')); - } - }); } onReport(event: AnswerReportEvent): void { const target = this.answerAt(event.index); - if (!target) { - return; - } - this.patchAnswer(event.index, {reported: true}); - this.aiSolutions.sendFeedback(this.solutionId, target.step, {answer: target.answer.content, problem: event.problem, comment: event.comment}).subscribe({ - next: () => this.store.dispatch(new ActionNotificationShow({ + if (target) { + aiReportAnswer(event, this.answerFeedback(event.index, target), () => this.store.dispatch(new ActionNotificationShow({ message: this.translate.instant('ai-assistant.feedback.thanks'), type: 'success', modern: true, target: 'solution-creator-chat', verticalPosition: 'bottom', horizontalPosition: 'center' - })), - error: () => { - this.patchAnswer(event.index, {reported: false}); - this.showErrorMessage(this.translate.instant('ai-assistant.feedback.failed')); - } - }); + }))); + } + } + + private answerFeedback(index: number, target: {answer: GeneralChatMessage; step: SolutionStep}): AiAnswerFeedback { + return { + patch: patch => this.patchAnswer(index, patch), + send: feedback => this.aiSolutions.sendFeedback(this.solutionId, target.step, {answer: target.answer.content, ...feedback}), + failed: () => this.showErrorMessage(this.translate.instant('ai-assistant.feedback.failed')) + }; } private answerAt(index: number): {answer: GeneralChatMessage; step: SolutionStep} | null { @@ -1327,7 +1232,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe takeUntil(this.cancelPending$) ).subscribe(value => { this.solutionInfo = value; - this.solutionDescriptor = this.solutionInfo.data.solutionDescriptor; }); } @@ -1336,7 +1240,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe takeUntil(this.cancelPending$) ).subscribe(value => { this.solutionInfo = value; - this.dashboardsOverview = this.solutionInfo.data.dashboardsOverview; }); } @@ -1360,7 +1263,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe updatedSolution($event: SolutionCreatorInfo) { if ($event.id === this.solutionId) { - this.solutionName = $event.data?.solutionTitle; this.solutionInfo = $event; } } @@ -1503,12 +1405,9 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.messages.set(tagged.map(item => item.message)); const stepState = this.solutionInfo.states[this.solutionStep()]; if (stepState?.status === SolutionStepStatus.READY) { - this.solutionName = this.solutionInfo.data?.solutionTitle; if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { - this.solutionDescriptor = this.solutionInfo.data.solutionDescriptor; } if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { - this.dashboardsOverview = this.solutionInfo.data.dashboardsOverview; } this.isReadyStep.set(true); this.skipInterviewAllowed.set(false); @@ -1544,7 +1443,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.clearWork(); this.pickedView.set(null); this.json.set(false); - this.jsonEditing.set(false); this.installProgress.set(null); this.failedAt.set('step'); this.uninstalledAt.set(null); @@ -1555,14 +1453,13 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.messages.set([]); this.messageSteps = []; this.closingPatch.set({}); + this.stopping.set(false); this.stopLoadingState(); this.creatorStep.set(null); this.promptInput?.reset(); this.showMoreExamples.set(false); - this.solutionDescriptor = undefined; this.solutionId = undefined; this.solutionInfo = undefined; - this.solutionName = undefined; } private initPredefinedSolution(): void { @@ -1771,7 +1668,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.messageSteps = this.messageSteps.slice(0, -1); } this.isGenerating.set(true); - this.startWork([{text: 'solution-creator.work-thinking', delay: 0}], 'think', undefined, since); + this.startWork([{text: 'solution-creator.work-thinking', delay: 0}], 'think', since); } timer(SolutionChatComponent.DESIGN_POLL_MS, SolutionChatComponent.DESIGN_POLL_MS).pipe( take(SolutionChatComponent.DESIGN_POLL_LIMIT), @@ -1802,9 +1699,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe this.failure.set(null); this.isGenerating.set(true); let messages: Array<{text: string; delay: number}>; - let estimateWaitTime: number; if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { - estimateWaitTime = 30000; messages = [ { text: 'solution-creator.step-loading-updating-entities', delay: 0 }, { text: 'solution-creator.step-loading-restructuring-roles', delay: 10000 }, @@ -1814,7 +1709,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe ]; } else if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { if (kind === 'design') { - estimateWaitTime = 30000; messages = [ { text: 'solution-creator.step-loading-designing-dashboards-structure', delay: 0 }, { text: 'solution-creator.step-loading-designing-dashboards-states', delay: 10000 }, @@ -1822,14 +1716,12 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe { text: 'solution-creator.step-loading-adding-finishing-touches', delay: 10000 }, ]; } else if (kind === 'sync') { - estimateWaitTime = 20000; messages = [ { text: 'solution-creator.step-loading-evaluating-solution-changes', delay: 0 }, { text: 'solution-creator.step-loading-reevaluating-use-cases', delay: 5000 }, { text: 'solution-creator.step-loading-finalizing', delay: 15000 }, ]; } else { - estimateWaitTime = 90000; messages = [ { text: 'solution-creator.step-loading-creating-entities', delay: 0 }, { text: 'solution-creator.step-loading-configuring-devices', delay: 10000 }, @@ -1850,7 +1742,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { this.paneOpen.set(true); } - return this.startWork(messages, creating ? 'install' : 'gen', estimateWaitTime, since); + return this.startWork(messages, creating ? 'install' : 'gen', since); } private static storeWork(solutionId: string, value: string): void { @@ -1880,7 +1772,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe return start > 0 && start <= Date.now() ? start : Date.now(); } - private startWork(messages: Array<{text: string; delay: number}>, kind: 'think' | 'gen' | 'install', _estimate?: number, + private startWork(messages: Array<{text: string; delay: number}>, kind: 'think' | 'gen' | 'install', since = Date.now()): {close: () => void} { const making = this.making(); this.clearWork(); @@ -1910,7 +1802,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe } toggleJson(): void { - this.jsonEditing.set(false); this.json.set(!this.json()); } @@ -1929,7 +1820,6 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe closePane(): void { this.paneOpen.set(false); this.json.set(false); - this.jsonEditing.set(false); } toggleMoreExamples(): void { diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts index 36ce683376..c2c801f634 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts @@ -124,7 +124,7 @@ export class AlarmRulesTableConfig extends EntityTableConfig this.defaultSortOrder = {property: 'createdTime', direction: Direction.DESC}; - if (this.pageMode && this.authUser.authority === Authority.TENANT_ADMIN && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { + if (this.pageMode && this.userPermissionsService.isAiAvailable()) { this.aiAssistantConfig = { view: { listView: AiAssistantViewType.ALARM_LIST diff --git a/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts b/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts index 54e71516cb..969c80b50a 100644 --- a/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts @@ -120,7 +120,7 @@ export class CalculatedFieldsTableConfig extends EntityTableConfig batches.flat()) - ).subscribe(affected => { + this.panelService.updatedDataBatches$.subscribe(affected => { const dashboards = affected.filter(entityId => entityId.entityType === EntityType.DASHBOARD); if (dashboards.length) { if (dashboards.some(dashboard => dashboard.id === this.currentDashboardId)) { diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.scss b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.scss index b1fa47a8a2..839a04ec90 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.scss @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 @use '@angular/material' as mat; -@import "../theme/app-theme.scss"; +@import "../theme/app-theme-palette"; $tb-primary-50: map_get(mat.$m2-teal-palette, 50); $tb-warn: mat.m2-get-color-from-palette(map-get($tb-theme, warn), text); diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index 7d9c62d84f..39a74353e4 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -271,7 +271,7 @@ import { import { ConverterLibraryModelAutocompleteComponent } from '@home/components/converter/converter-library-model-autocomplete.component'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack.component'; import { LicenseHandOffDialogComponent } from '@home/components/license/license-hand-off-dialog.component'; @@ -487,7 +487,7 @@ import { LicenseHandOffDialogComponent } from '@home/components/license/license- EntityDebugSettingsButtonComponent, NotificationBellModule, GithubBadgeModule, - AiModule, + AiCoreModule, ], exports: [ LicenseHandOffDialogComponent, diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html deleted file mode 100644 index 878b6be563..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html +++ /dev/null @@ -1,65 +0,0 @@ - - - - - {{ 'widgets.cluster-info.service-id' | translate }} - - - {{ serviceData.serviceId }} - - - - - {{ 'widgets.cluster-info.service-type' | translate }} - - - {{ serviceData.serviceType }} - - - - - {{ 'widgets.system-info.cpu' | translate }} - - - {{ serviceData.cpuUsage }}% - - - - - {{ 'widgets.system-info.ram' | translate }} - - - {{ serviceData.memoryUsage }}% - - - - - {{ 'widgets.system-info.disk' | translate }} - - - {{ serviceData.discUsage }}% - - - - -
    -widgets.cluster-info.no-data diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss deleted file mode 100644 index c0ec6dcd57..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -:host { - span.no-data-found { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } - - .tb-resource-usage { - cursor: default; - &.tb-status-warn, &.tb-status-critical { - position: relative; - overflow: visible; - &:before { - position: absolute; - top: 15px; - left: -24px; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 1; - } - } - &.tb-status-warn { - color: var(--tb-warning); - &:before { - content: "warning"; - color: var(--tb-warning); - } - } - &.tb-status-critical { - color: var(--tb-crit); - &:before { - content: "warning"; - color: var(--tb-crit); - } - } - } -} - -:host ::ng-deep { - .mdc-data-table__header-cell { - font-weight: 500; - font-size: 11px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - } - .mdc-data-table__cell { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts deleted file mode 100644 index 6ec9483f6e..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { AfterViewInit, Component, NgZone, OnInit, ViewChild } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { CollectionViewer, DataSource } from '@angular/cdk/collections'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { emptyPageData, PageData } from '@shared/models/page/page-data'; -import { MAX_SAFE_PAGE_SIZE, PageLink } from '@shared/models/page/page-link'; -import { catchError, map, publishReplay, refCount, share } from 'rxjs/operators'; -import { MatSort } from '@angular/material/sort'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { EntityDataUpdate, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; -import { EntityKeyType } from '@shared/models/query/query.models'; -import { TranslateService } from '@ngx-translate/core'; - -export interface SystemInfoData { - serviceId: string; - serviceType: string; - cpuUsage: number; - cpuCount: number; - memoryUsage: number; - totalMemory: number; - discUsage: number; - totalDiscSpace: number; -} - -@Component({ - selector: 'tb-cluster-info-table', - templateUrl: './cluster-info-table.component.html', - styleUrls: ['./cluster-info-table.component.scss'], - standalone: false -}) -export class ClusterInfoTableComponent extends PageComponent implements OnInit, AfterViewInit { - - @ViewChild(MatSort) sort: MatSort; - - displayedColumns = ['serviceId', 'serviceType', 'cpuUsage', 'memoryUsage', 'discUsage']; - - dataSource: SystemInfoDataSource; - - pageLink: PageLink; - - constructor(protected store: Store, - private telemetryWsService: TelemetryWebsocketService, - private translate: TranslateService, - private zone: NgZone) { - super(store); - } - - ngOnInit() { - this.dataSource = new SystemInfoDataSource(this.telemetryWsService, this.zone); - const sortOrder: SortOrder = { - property: 'serviceId', - direction: Direction.ASC - }; - this.pageLink = new PageLink(MAX_SAFE_PAGE_SIZE, 0, null, sortOrder); - this.dataSource.loadData(this.pageLink); - } - - ngAfterViewInit() { - this.sort.sortChange.subscribe(() => this.updateData()); - } - - updateData() { - this.pageLink.sortOrder.property = this.sort.active; - this.pageLink.sortOrder.direction = Direction[this.sort.direction.toUpperCase()]; - this.dataSource.loadData(this.pageLink); - } - - statusClass(value: number): string { - let status = ''; - if (value > 85) { - status = 'tb-status-critical'; - } else if (value > 75) { - status = 'tb-status-warn'; - } - return status; - } - - infoTooltip(serviceData: SystemInfoData, type: 'cpu' | 'ram' | 'disc'): string { - let tooltip = ''; - let value: number; - switch (type) { - case 'cpu': - value = serviceData.cpuUsage; - tooltip += value + ' / 100 %'; - break; - case 'ram': - value = serviceData.memoryUsage; - const memoryUsage = serviceData.memoryUsage; - const totalMemory = serviceData.totalMemory / 1073741824; - const usedMemory = (totalMemory * (memoryUsage / 100)).toFixed(0); - tooltip += usedMemory + ' / ' + totalMemory.toFixed(0) + ' Gb'; - break; - case 'disc': - value = serviceData.discUsage; - const discUsage = serviceData.discUsage; - const totalDiscSpace = serviceData.totalDiscSpace / 1073741824; - const usedDisc = (totalDiscSpace * (discUsage / 100)).toFixed(0); - tooltip += usedDisc + ' / ' + totalDiscSpace.toFixed(0) + ' Gb'; - break; - } - if (value > 85) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-critical-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-critical-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-critical-text'); - break; - } - } else if (value > 75) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-warning-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-warning-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-warning-text'); - break; - } - } - return tooltip; - } -} - -export class SystemInfoDataSource implements DataSource { - - private systemDataSubject = new BehaviorSubject([]); - private pageDataSubject = new BehaviorSubject>(emptyPageData()); - - public pageData$ = this.pageDataSubject.asObservable(); - - private allSystemData: Observable>; - - private telemetrySubscriber: TelemetrySubscriber; - - constructor(private telemetryWsService: TelemetryWebsocketService, - private zone: NgZone) { - } - - connect(collectionViewer: CollectionViewer): Observable> { - return this.systemDataSubject.asObservable(); - } - - disconnect(collectionViewer: CollectionViewer): void { - this.systemDataSubject.complete(); - this.pageDataSubject.complete(); - if (this.telemetrySubscriber) { - this.telemetrySubscriber.unsubscribe(); - this.telemetrySubscriber = null; - } - } - - loadData(pageLink: PageLink): void { - this.getAllSystemData().pipe( - map((data) => pageLink.filterData(data)), - catchError(() => of(emptyPageData())), - ).subscribe( - (pageData) => { - this.onSystemData(pageData.data); - this.pageDataSubject.next(pageData); - } - ); - } - - getAllSystemData(): Observable> { - if (!this.allSystemData) { - this.telemetrySubscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( - this.telemetryWsService, { type: AliasFilterType.apiUsageState }, this.zone, - [ { key: 'clusterSystemData', type: EntityKeyType.TIME_SERIES } ]); - this.telemetrySubscriber.subscribe(); - this.allSystemData = this.telemetrySubscriber.entityData$.pipe( - map((update) => this.toSystemInfoData(update)), - publishReplay(1), - refCount() - ); - } - return this.allSystemData; - } - - private toSystemInfoData(entityDataUpdate: EntityDataUpdate): Array { - const entityData = entityDataUpdate.data?.data ? entityDataUpdate.data?.data : entityDataUpdate.update; - if (entityData && entityData.length) { - const latest = entityData[0].latest; - if (latest && latest[EntityKeyType.TIME_SERIES]) { - const latestTs = latest[EntityKeyType.TIME_SERIES]; - const tsValue = latestTs.clusterSystemData; - if (tsValue && tsValue.value) { - return JSON.parse(tsValue.value); - } - } - } - return []; - } - - protected onSystemData(data: SystemInfoData[]) { - this.systemDataSubject.next(data); - } - - isEmpty(): Observable { - return this.systemDataSubject.pipe( - map((entities) => !entities.length), - share() - ); - } - - total(): Observable { - return this.pageDataSubject.pipe( - map((pageData) => pageData.totalElements), - share() - ); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html deleted file mode 100644 index 33345de243..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html +++ /dev/null @@ -1,71 +0,0 @@ - - diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss deleted file mode 100644 index 168d3aaf4c..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - - .tb-title { - margin-top: 8px; - } - - .tb-info-icon { - color: rgba(0, 0, 0, 0.12); - font-size: 16px; - width: 16px; - height: 16px; - line-height: 15px; - vertical-align: middle; - } - - .tb-features-list { - overflow: auto; - } - - .mat-grid-tile.tb-feature-tile { - overflow: visible; - } - - .tb-feature-button { - height: 50px; - display: flex; - overflow: hidden; - flex-direction: column; - justify-content: center; - padding: 12px; - background: #FFFFFF; - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - @media #{$mat-md-lg} { - height: 22px; - padding: 0 8px; - } - &:hover { - border: 1px solid rgba(0, 0, 0, 0.12); - box-shadow: 0 4px 10px rgba(23, 33, 90, 0.08); - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 20px; - color: rgba(0, 0, 0, 0.12); - font-weight: 600; - position: relative; - background: #F4F4F4; - border-radius: 4px; - width: 24px; - height: 24px; - padding: 2px; - margin-right: 8px; - vertical-align: middle; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.configured { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts deleted file mode 100644 index f521e95201..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { FeaturesInfo } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-configured-features', - templateUrl: './configured-features.component.html', - styleUrls: ['./home-page-widget.scss', './configured-features.component.scss'], - standalone: false -}) -export class ConfiguredFeaturesComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - featuresInfo: FeaturesInfo; - rowHeight = '50px'; - gutterSize = '12px'; - colspan = 2; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - const isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - const isLtMd = this.breakpointObserver.isMatched(MediaBreakpoints['lt-md']); - this.rowHeight = isMdLg ? '22px' : '50px'; - this.gutterSize = isMdLg ? '8px' : '12px'; - this.colspan = isLtMd ? 3 : 2; - this.observeBreakpointSubscription = this.breakpointObserver - .observe([MediaBreakpoints['md-lg'], MediaBreakpoints['lt-md']]) - .subscribe((state: BreakpointState) => { - if (state.breakpoints[MediaBreakpoints['md-lg']]) { - this.rowHeight = '22px'; - this.gutterSize = '8px'; - } else { - this.rowHeight = '50px'; - this.gutterSize = '12px'; - } - if (state.breakpoints[MediaBreakpoints['lt-md']]) { - this.colspan = 3; - } else { - this.colspan = 2; - } - this.cd.markForCheck(); - } - ); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getFeaturesInfo() : of(null)).subscribe( - (featuresInfo) => { - this.featuresInfo = featuresInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - featureTooltip(configured: boolean): string { - if (configured) { - return this.translate.instant('widgets.configured-features.feature-configured'); - } else { - return this.translate.instant('widgets.configured-features.feature-not-configured'); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts index 55ea62bb7d..b44d03a596 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts @@ -4,9 +4,6 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@app/shared/shared.module'; -import { ClusterInfoTableComponent } from '@home/components/widget/lib/home-page/cluster-info-table.component'; -import { ConfiguredFeaturesComponent } from '@home/components/widget/lib/home-page/configured-features.component'; -import { VersionInfoComponent } from '@home/components/widget/lib/home-page/version-info.component'; import { DocLinksWidgetComponent } from '@home/components/widget/lib/home-page/doc-links-widget.component'; import { DocLinkComponent } from '@home/components/widget/lib/home-page/doc-link.component'; import { AddDocLinkDialogComponent } from '@home/components/widget/lib/home-page/add-doc-link-dialog.component'; @@ -15,7 +12,6 @@ import { GettingStartedWidgetComponent } from '@home/components/widget/lib/home- import { GettingStartedCompletedDialogComponent } from '@home/components/widget/lib/home-page/getting-started-completed-dialog.component'; -import { LicenseUsageInfoComponent } from '@home/components/widget/lib/home-page/license-usage-info.component'; import { UsageInfoWidgetComponent } from '@home/components/widget/lib/home-page/usage-info-widget.component'; import { QuickLinksWidgetComponent } from '@home/components/widget/lib/home-page/quick-links-widget.component'; import { QuickLinkComponent } from '@home/components/widget/lib/home-page/quick-link.component'; @@ -29,16 +25,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone @NgModule({ declarations: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, @@ -52,16 +44,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone IotHubComponentsModule ], exports: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html deleted file mode 100644 index 809294b972..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html +++ /dev/null @@ -1,80 +0,0 @@ - -
    -
    -
    -
    widgets.license-info.title
    -
    - {{ 'widgets.license-info.view-all' | translate }} -
    -
    - -
    -
    -
    - - {{ statusIcon(licenseUsageInfo?.devicesCount, licenseUsageInfo?.maxDevices) }} - {{ 'widgets.license-info.devices-info' | translate: { count: licenseUsageInfo?.devicesCount, max: licenseUsageInfo?.maxDevices} }} -
    -
    - - {{ statusIcon(licenseUsageInfo?.assetsCount, licenseUsageInfo?.maxAssets) }} - {{ 'widgets.license-info.assets-info' | translate: { count: licenseUsageInfo?.assetsCount, max: licenseUsageInfo?.maxAssets} }} -
    - @if (showEdges) { -
    - - {{ statusIcon(licenseUsageInfo?.edgesCount, licenseUsageInfo?.maxEdges) }} - {{ 'widgets.license-info.edges-info' | translate: { count: licenseUsageInfo?.edgesCount, max: licenseUsageInfo?.maxEdges} }} -
    - } - @if (!isMdLg) { -
    - - check - {{ 'widgets.license-info.dashboards-info' | translate: { count: licenseUsageInfo?.dashboardsCount, max: 0} }} -
    - } - @if (!isMdLg) { -
    - - check - {{ 'widgets.license-info.integrations-info' | translate: { count: licenseUsageInfo?.integrationsCount, max: 0} }} -
    - } -
    - @if (!isMdLg) { -
    -
    - - check - {{ 'widgets.license-info.community-support' | translate }} -
    -
    - - {{ licenseUsageInfo?.whiteLabelingEnabled ? 'check' : 'close' }} - {{ 'widgets.license-info.white-labeling' | translate }} -
    -
    - - check - {{ 'widgets.license-info.unlimited-datapoints-and-messages' | translate }} -
    -
    - - check - {{ 'widgets.license-info.unlimited-api-calls' | translate }} -
    -
    - } -
    -
    -
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss deleted file mode 100644 index b9ef44a550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-content { - width: 100%; - height: 100%; - } - - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-title { - font-style: normal; - font-weight: 500; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - } - } - - .tb-view-all, .tb-license-portal { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-license-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - display: flex; - flex-direction: column; - @media #{$mat-md-lg} { - padding: 4px; - } - } - - .tb-plan-link { - font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - position: relative; - border-radius: 4px; - width: 22px; - height: 22px; - margin-right: 8px; - @media #{$mat-md-lg} { - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.ok, &.disabled { - .tb-feature-status { - font-size: 20px; - line-height: 20px; - font-weight: 600; - padding: 1px; - vertical-align: sub; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - padding: 2px; - } - } - } - &.ok { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - &.disabled { - .tb-feature-status { - color: rgba(0, 0, 0, 0.12); - background: #F4F4F4; - } - } - &.critical { - color: var(--tb-crit); - .tb-feature-status { - line-height: 24px; - font-size: 24px; - font-weight: normal; - padding: 0; - vertical-align: bottom; - @media #{$mat-md-lg} { - font-size: 18px; - line-height: 18px; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts deleted file mode 100644 index 176cac3229..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { LicenseUsageInfo } from '@shared/models/settings.models'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-license-usage-info', - templateUrl: './license-usage-info.component.html', - styleUrls: ['./license-usage-info.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class LicenseUsageInfoComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - licenseUsageInfo: LicenseUsageInfo; - isMdLg = false; - authState = getCurrentAuthState(this.store); - showEdges = this.authState.licenseVersion > 1 && this.authState.edgesSupportEnabled && this.authState.edgeEnabled; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - this.isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - this.observeBreakpointSubscription = this.breakpointObserver - .observe(MediaBreakpoints['md-lg']) - .subscribe((state: BreakpointState) => { - this.isMdLg = state.matches; - this.cd.markForCheck(); - }); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getLicenseUsageInfo() : of(null)).subscribe( - (licenseUsageInfo) => { - this.licenseUsageInfo = licenseUsageInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - statusIcon(count?: number, max?: number): string { - let icon = 'check'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - icon = 'warning'; - } - } - return icon; - } - - statusClass(count?: number, max?: number): string { - let className = 'ok'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - className = 'critical'; - } - } - return className; - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html deleted file mode 100644 index b222ea9477..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html +++ /dev/null @@ -1,53 +0,0 @@ - -
    -
    -
    -
    widgets.version-info.title
    -
    - {{ 'widgets.version-info.contact-us' | translate }} -
    -
    -
    -
    - -
    {{ updateMessage?.currentVersion }}
    -
    -
    -
    -
    - @if (updateMessage?.updateAvailable) { - - } @else { -
    -
    check
    -
    widgets.version-info.version-is-up-to-date
    -
    - } -
    -
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss deleted file mode 100644 index c3e815d550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - margin-bottom: 8px; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-contact-us { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-version-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - overflow: hidden; - white-space: nowrap; - @media #{$mat-lt-md} { - padding: 16px; - } - @media #{$mat-md-lg} { - padding: 4px; - } - &.up-to-date { - position: relative; - box-shadow: none; - border: none; - white-space: initial; - text-align: center; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 10px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - - .tb-version-link { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - - .tb-version { - font-weight: 500; - font-size: 18px; - line-height: 24px; - letter-spacing: 0.15px; - color: rgba(0, 0, 0, 0.87); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 14px; - } - } - - .tb-upgrade { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - padding: 0; - overflow: hidden; - } - } - - .check-icon { - color: #198038; - font-weight: 600; - @media #{$mat-md-lg} { - font-size: 16px; - } - } - - .up-to-date-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts deleted file mode 100644 index 921a6ba0a3..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { UpdateMessage } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of } from 'rxjs'; - -@Component({ - selector: 'tb-version-info', - templateUrl: './version-info.component.html', - styleUrls: ['./home-page-widget.scss', './version-info.component.scss'], - standalone: false -}) -export class VersionInfoComponent extends PageComponent implements OnInit { - - authUser = getCurrentAuthUser(this.store); - updateMessage: UpdateMessage; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService) { - super(store); - } - - ngOnInit() { - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.checkUpdates() : of(null)).subscribe( - (updateMessage) => { - this.updateMessage = updateMessage; - this.cd.markForCheck(); - } - ); - } -} diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index 46c4435f5e..1d76d5d396 100644 --- a/ui-ngx/src/app/modules/home/home.component.html +++ b/ui-ngx/src/app/modules/home/home.component.html @@ -58,7 +58,7 @@ -
    +
    @if ((homeService.hideMainToolbar$ | async) === false) {
    @if (aiAvailable) { - + } diff --git a/ui-ngx/src/app/modules/home/home.component.ts b/ui-ngx/src/app/modules/home/home.component.ts index 2ebc079a87..0bee0037c9 100644 --- a/ui-ngx/src/app/modules/home/home.component.ts +++ b/ui-ngx/src/app/modules/home/home.component.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { AfterViewInit, Component, computed, ElementRef, Inject, OnDestroy, OnInit, Renderer2, signal, ViewChild, inject } from '@angular/core'; +import { AfterViewInit, Component, computed, createNgModule, ElementRef, Inject, Injector, OnDestroy, OnInit, Renderer2, signal, ViewChild, ViewContainerRef, inject } from '@angular/core'; import { combineLatest, Observable, skip, startWith, Subject } from 'rxjs'; import { select, Store } from '@ngrx/store'; import { debounceTime, distinctUntilChanged, map, share, take, takeUntil } from 'rxjs/operators'; @@ -76,6 +76,22 @@ export class HomeComponent extends PageComponent implements AfterViewInit, OnIni readonly aiAvailable = this.tourService.aiAvailable(); + readonly aiPanelLoaded = signal(false); + + private injector = inject(Injector); + + @ViewChild('aiPanelHost', {read: ViewContainerRef}) set aiPanelHost(host: ViewContainerRef) { + if (host && !this.aiPanelLoaded()) { + Promise.all([import('@home/components/ai/ai.module'), import('@home/components/ai/ai-assistant-panel.component')]) + .then(([{AiModule}, {AiAssistantPanelComponent}]) => { + if (!this.aiPanelLoaded()) { + host.createComponent(AiAssistantPanelComponent, {ngModuleRef: createNgModule(AiModule, this.injector)}); + this.aiPanelLoaded.set(true); + } + }); + } + } + constructor(protected store: Store, @Inject(WINDOW) private window: Window, private activeComponentService: ActiveComponentService, diff --git a/ui-ngx/src/app/modules/home/home.module.ts b/ui-ngx/src/app/modules/home/home.module.ts index cabe5aebbb..3e090e0ffb 100644 --- a/ui-ngx/src/app/modules/home/home.module.ts +++ b/ui-ngx/src/app/modules/home/home.module.ts @@ -12,7 +12,7 @@ import { MenuToggleComponent } from '@modules/home/menu/menu-toggle.component'; import { SideMenuComponent } from '@modules/home/menu/side-menu.component'; import { NotificationBellModule } from '@home/components/notification/notification-bell.module'; import { GithubBadgeModule } from '@home/components/github-badge/github-badge.module'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; import { GotoMenuComponent } from '@home/menu/goto-menu.component'; @NgModule({ @@ -30,7 +30,7 @@ import { GotoMenuComponent } from '@home/menu/goto-menu.component'; NotificationBellModule, GithubBadgeModule, HomeRoutingModule, - AiModule + AiCoreModule ] }) export class HomeModule { } diff --git a/ui-ngx/src/app/modules/home/pages/admin/license-management.component.ts b/ui-ngx/src/app/modules/home/pages/admin/license-management.component.ts index 7da4fc040a..d0d21b4051 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/license-management.component.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/license-management.component.ts @@ -29,8 +29,6 @@ import { licenseLimitWarn, licenseMeterWidth } from '@home/components/license/license-actions.service'; -import { select } from '@ngrx/store'; -import { take } from 'rxjs/operators'; import { resolveSendErrorMessage } from '@core/utils'; enum ManageLicenseState { diff --git a/ui-ngx/src/app/modules/home/pages/admin/mail-server.component.ts b/ui-ngx/src/app/modules/home/pages/admin/mail-server.component.ts index bfa4fc26d1..81974c7b92 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/mail-server.component.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/mail-server.component.ts @@ -26,7 +26,7 @@ import { Authority } from '@shared/models/authority.enum'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; import { Subject } from 'rxjs'; -import { filter, switchMap, takeUntil } from 'rxjs/operators'; +import { switchMap, takeUntil } from 'rxjs/operators'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { DomainSchema, domainSchemaTranslations, } from '@shared/models/oauth2.models'; import { WINDOW } from '@core/services/window.service'; @@ -149,8 +149,7 @@ export class MailServerComponent extends PageComponent implements OnInit, OnDest this.loginProcessingUrl = data.loginProcessingUrl; this.initTemplates(data.mailConfigTemplate); this.applySettings(data.adminSettings); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'MAIL_SERVER' && !this.mailSettings.dirty), + this.aiAssistantPanelService.customizationReload$('MAIL_SERVER', () => !this.mailSettings.dirty).pipe( switchMap(() => this.adminService.getAdminSettings('mail', false, {ignoreLoading: true})), takeUntil(this.destroy$) ).subscribe(settings => { diff --git a/ui-ngx/src/app/modules/home/pages/admin/mail-templates.component.ts b/ui-ngx/src/app/modules/home/pages/admin/mail-templates.component.ts index 89127da557..270125773f 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/mail-templates.component.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/mail-templates.component.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 import { Component, DestroyRef, inject, OnInit } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { filter, switchMap } from 'rxjs/operators'; +import { switchMap } from 'rxjs/operators'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { PageComponent } from '@shared/components/page.component'; import { HasDirtyFlag } from '@core/guards/confirm-on-exit.guard'; @@ -88,8 +88,7 @@ export class MailTemplatesComponent extends PageComponent implements OnInit, Has '| numlist bullist outdent indent | blocks | removeformat code | fullscreen'; } this.applySettings(this.route.snapshot.data.mailTemplatesSettings); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'MAIL_TEMPLATES' && !this.isDirty), + this.aiAssistantPanelService.customizationReload$('MAIL_TEMPLATES', () => !this.isDirty).pipe( switchMap(() => this.wl.getMailTemplates(true)), takeUntilDestroyed(this.destroyRef) ).subscribe(settings => this.applySettings(settings)); diff --git a/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts index fd2a5bc17b..54a792d1c6 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts @@ -24,7 +24,6 @@ import { UserPermissionsService } from '@core/http/user-permissions.service'; import { NotificationTargetConfigType, NotificationTargetConfigTypeInfoMap } from '@shared/models/notification.models'; import { EntityType } from '@shared/models/entity-type.models'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { filter } from 'rxjs/operators'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; @Component({ @@ -69,8 +68,7 @@ export class TwoFactorAuthSettingsComponent extends PageComponent implements OnI ngOnInit() { this.build2faSettingsForm(); this.loadSettings(); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'TWO_FACTOR' && !this.twoFaFormGroup.dirty), + this.aiAssistantPanelService.customizationReload$('TWO_FACTOR', () => !this.twoFaFormGroup.dirty).pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(() => this.loadSettings()); } diff --git a/ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts b/ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts index 32910e4d09..c2c6c50570 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/white-labeling.component.ts @@ -120,7 +120,7 @@ export class WhiteLabelingComponent extends PageComponent implements OnInit, Has this.buildWhiteLabelingSettingsForm(); this.loadWhiteLabelingParams(); this.aiAssistantPanelService.whiteLabelingSaved$.pipe( - filter(target => (target === 'LOGIN') === !!this.isLoginWl), + filter(target => (target === 'LOGIN') === !!this.isLoginWl && !this.wlSettings.dirty), takeUntilDestroyed(this.destroyRef) ).subscribe(() => this.loadWhiteLabelingParams()); } diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-page.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-page.module.ts new file mode 100644 index 0000000000..5c733a4e1c --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-page.module.ts @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { RouterModule } from '@angular/router'; +import { SharedModule } from '@shared/shared.module'; +import { AiModule } from '@home/components/ai/ai.module'; +import { SolutionChatModule } from '@home/components/ai/solution/solution-chat.module'; +import { AiAssistantComponent } from '@home/pages/ai-assistant/ai-assistant.component'; +import { AiCliGuideComponent } from '@home/pages/ai-assistant/cli/ai-cli-guide.component'; +import { AiSlotsPipe } from '@home/pages/ai-assistant/cli/ai-slots.pipe'; + +@NgModule({ + declarations: [ + AiAssistantComponent, + AiCliGuideComponent, + AiSlotsPipe + ], + imports: [ + CommonModule, + SharedModule, + AiModule, + SolutionChatModule, + RouterModule.forChild([{path: '', component: AiAssistantComponent}]) + ] +}) +export class AiAssistantPageModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts index 7eb5bd79a3..282b123c93 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant-routing.module.ts @@ -4,22 +4,20 @@ import { inject, NgModule } from '@angular/core'; import { Router, RouterModule, Routes } from '@angular/router'; import { Authority } from '@shared/models/authority.enum'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { MenuId } from '@core/services/menu.models'; -import { AiAssistantComponent } from '@home/pages/ai-assistant/ai-assistant.component'; import { NEW_SOLUTION_ID } from '@shared/models/solution-creator.models'; const routes: Routes = [ { path: 'ai-assistant', - component: AiAssistantComponent, + loadChildren: () => import('./ai-assistant-page.module').then(m => m.AiAssistantPageModule), data: { breadcrumb: { menuId: MenuId.ai_assistant }, auth: [Authority.TENANT_ADMIN], canActivate: (userPermissionsService: UserPermissionsService): boolean => { - return userPermissionsService.isAiEnabled() && userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return userPermissionsService.isAiAvailable(); }, } }, diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss index 247317a445..943542683a 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +@use '../../components/ai/ai-icon-button' as *; @import "constants"; :host { @@ -18,38 +19,7 @@ } .ai-rail .ai-ib, .ai-bar-chats { - position: relative; - flex: none; - width: 32px; - height: 32px; - min-width: var(--chat-tap); - min-height: var(--chat-tap); - padding: 0; - border: 0; - border-radius: 8px; - background: none; - color: var(--tb-ink-60); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: background-color .15s ease, color .15s ease; - - &:hover { - background: rgba(0, 0, 0, 0.06); - color: var(--tb-ink); - } - - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 1px; - } - - .mat-icon { - font-size: 19px; - width: 19px; - height: 19px; - } + @include ai-icon-button($color: var(--tb-ink-60)); } .ai-panel-icon { diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts index c5b63c0312..3db450a872 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts @@ -4,10 +4,11 @@ import { TourService } from '@core/services/tour.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AiChatService } from '@core/http/ai-chat.service'; import { + ChangeDetectionStrategy, Component, computed, - effect, DestroyRef, + effect, ElementRef, HostListener, inject, @@ -52,6 +53,7 @@ export interface AiChatsGroup { } @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-assistant', templateUrl: './ai-assistant.component.html', styleUrls: ['./ai-assistant.component.scss'], diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts index 73e412e3eb..a92dd5563d 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.module.ts @@ -1,22 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { SharedModule } from '@shared/shared.module'; -import { AiAssistantComponent } from '@home/pages/ai-assistant/ai-assistant.component'; -import { AiModule } from '@home/components/ai/ai.module'; import { AiAssistantRoutingModule } from '@home/pages/ai-assistant/ai-assistant-routing.module'; -import { SolutionChatModule } from '@home/components/ai/solution/solution-chat.module'; @NgModule({ - declarations: [ - AiAssistantComponent - ], imports: [ - CommonModule, - SharedModule, - AiModule, - SolutionChatModule, AiAssistantRoutingModule ] }) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html similarity index 94% rename from ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html rename to ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html index 40d668b50c..f2efef31ec 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.html @@ -122,7 +122,7 @@
  • {{ 'ai-assistant.cli.setup.accept-folder' | translate }} -

    {{ 'ai-assistant.cli.setup.accept-before' | translate }}thingsboard-project.{{ 'ai-assistant.cli.setup.accept-after' | translate }}

    +

    @for (part of 'ai-assistant.cli.setup.accept' | tbAiSlots; track $index) {@if (part.slot === 'folder') {thingsboard-project.} @else {{{ part.text }}}}

  • {{ 'ai-assistant.cli.setup.paste-url' | translate }} @@ -138,7 +138,7 @@
  • {{ 'ai-assistant.cli.setup.start-agent' | translate }}

    {{ 'ai-assistant.cli.setup.start-agent-text' | translate }}

    -

    {{ 'ai-assistant.cli.setup.both-agents' | translate }}claude{{ 'ai-assistant.cli.setup.both-agents-or' | translate }}antigravity.

    +

    @for (part of 'ai-assistant.cli.setup.both-agents' | tbAiSlots; track $index) {@switch (part.slot) {@case ('claude') {claude} @case ('antigravity') {antigravity.} @default {{{ part.text }}}}}

    {{ 'ai-assistant.cli.setup.come-back-folder' | translate }}

  • @@ -166,7 +166,7 @@
  • {{ 'ai-assistant.cli.setup.agent-restart' | translate }} -

    {{ 'ai-assistant.cli.setup.restart-before' | translate }}/exit{{ 'ai-assistant.cli.setup.restart-after' | translate }}

    +

    @for (part of 'ai-assistant.cli.setup.restart' | tbAiSlots; track $index) {@if (part.slot === 'exit') {/exit} @else {{{ part.text }}}}

    {{ 'ai-assistant.cli.setup.come-back' | translate }}

  • diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss similarity index 97% rename from ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss rename to ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss index 9b8ce8b762..6e4184f6a0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.scss @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -@use './ai-code-blocks' as *; +@use '../../../components/ai/ai-code-blocks' as *; +@use '../../../components/ai/ai-icon-button' as *; $ease: cubic-bezier(.2, 0, 0, 1); $motion: .15s; @@ -74,38 +75,7 @@ $hero-bg: #1b252c; } :host ::ng-deep .ai-ib { - position: relative; - flex: none; - width: 32px; - height: 32px; - min-width: var(--chat-tap); - min-height: var(--chat-tap); - padding: 0; - border: 0; - border-radius: 8px; - background: none; - color: var(--tb-ink-54); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: background-color $motion ease, color $motion ease; - - &:hover { - background: rgba(0, 0, 0, 0.06); - color: var(--tb-ink); - } - - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 1px; - } - - .mat-icon { - font-size: 19px; - width: 19px; - height: 19px; - } + @include ai-icon-button; } .ai-cli-scroll { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts similarity index 96% rename from ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts rename to ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts index 87d3bac663..519acf3895 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-guide.component.ts @@ -38,8 +38,9 @@ import { cliOs, CliOs, CliWay -} from '@home/components/ai/ai-cli.models'; -import { cliTerm, CliTerm } from '@home/components/ai/ai-cli-term'; +} from '@home/pages/ai-assistant/cli/ai-cli.models'; +import { writeStored } from '@core/local-storage/stored'; +import { cliTerm, CliTerm } from '@home/pages/ai-assistant/cli/ai-cli-term'; interface CliPicks { way?: CliWay; @@ -239,11 +240,7 @@ export class AiCliGuideComponent { private savePicks(): void { const picks: CliPicks = {way: this.way(), build: this.build()}; - try { - localStorage.setItem(AiCliGuideComponent.PICKS_KEY, JSON.stringify(picks)); - } catch { - return; - } + writeStored(AiCliGuideComponent.PICKS_KEY, JSON.stringify(picks)); } private static readPicks(): CliPicks { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts similarity index 99% rename from ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts rename to ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts index b38085e1c9..0b20f12b7b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli-term.ts @@ -8,7 +8,7 @@ import { CLI_VERSION, CliTermRow, CliTermSession -} from '@home/components/ai/ai-cli.models'; +} from '@home/pages/ai-assistant/cli/ai-cli.models'; export interface CliTerm { element: HTMLElement; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli.models.ts similarity index 100% rename from ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts rename to ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-cli.models.ts diff --git a/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts new file mode 100644 index 0000000000..9dd605d428 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/ai-assistant/cli/ai-slots.pipe.ts @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Pipe, PipeTransform } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; + +export interface AiSlotPart { + text?: string; + slot?: string; +} + +export function aiSlotParts(text: string): AiSlotPart[] { + const parts: AiSlotPart[] = []; + const pattern = /\{\{\s*([\w-]+)\s*\}\}/g; + let last = 0; + for (const match of text.matchAll(pattern)) { + if (match.index > last) { + parts.push({text: text.slice(last, match.index)}); + } + parts.push({slot: match[1]}); + last = match.index + match[0].length; + } + if (last < text.length) { + parts.push({text: text.slice(last)}); + } + return parts; +} + +@Pipe({ + name: 'tbAiSlots', + pure: false, + standalone: false +}) +export class AiSlotsPipe implements PipeTransform { + + private translate = inject(TranslateService); + private cacheKey: string; + private cached: AiSlotPart[] = []; + + transform(key: string): AiSlotPart[] { + const text: string = this.translate.instant(key); + const cacheKey = key + '\u0000' + text; + if (cacheKey !== this.cacheKey) { + this.cacheKey = cacheKey; + this.cached = aiSlotParts(text); + } + return this.cached; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts index 57a2007ee8..5ff3f81509 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-config.component.ts @@ -106,8 +106,8 @@ export class CustomMenuConfigComponent extends PageComponent implements OnInit, this.computeMaxIconNameBlockWidth(); }); this.computeMaxIconNameBlockWidth(); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'MENU' && event.menuId === this.customMenu.id.id), + this.aiAssistantPanelService.customizationReload$('MENU').pipe( + filter(event => event.menuId === this.customMenu.id.id), tap(event => { if (event.deleted) { this.forcePristine = true; diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts index 9e6d4bb364..b63cc50ae2 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts @@ -72,12 +72,10 @@ export class CustomMenuTableComponent implements OnInit { private destroyRef = inject(DestroyRef); ngOnInit() { - this.aiAssistantPanelService.customizationSaved$.pipe( + this.aiAssistantPanelService.customizationReload$('MENU').pipe( takeUntilDestroyed(this.destroyRef) - ).subscribe(event => { - if (event.kind === 'MENU') { - this.customMenuTableConfig.updateData(); - } + ).subscribe(() => { + this.customMenuTableConfig.updateData(); }); this.customMenuTableConfig.tableTitle = ''; this.customMenuTableConfig.headerComponent = CustomMenuTableHeaderComponent; diff --git a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts index 3072f54dbc..caf4c64770 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-map-table.component.ts @@ -24,7 +24,7 @@ import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { CustomTranslationService } from '@core/http/custom-translation.service'; import { ActivatedRoute, QueryParamsHandling, Router } from '@angular/router'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { catchError, debounceTime, distinctUntilChanged, map, skip, takeUntil } from 'rxjs/operators'; +import { catchError, debounceTime, distinctUntilChanged, filter, map, skip, takeUntil } from 'rxjs/operators'; import { isDefinedAndNotNull, isEqual, isNotEmptyStr, setByPath, unset } from '@core/utils'; import { DataSource } from '@angular/cdk/collections'; import { emptyPageData, PageData } from '@shared/models/page/page-data'; @@ -143,13 +143,10 @@ export class TranslationMapTableComponent extends PageComponent implements OnIni this.paginator.pageIndex = this.pageLink.page; this.paginator.pageSize = this.pageLink.pageSize; this.dataSource.loadTranslateInfo(this.pageLink, this.filterParams.value); - this.aiAssistantPanelService.customizationSaved$.pipe( + this.aiAssistantPanelService.customizationReload$('TRANSLATION').pipe( + filter(event => event.locale === this.localeCode), takeUntil(this.destroy$) - ).subscribe(event => { - if (event.kind === 'TRANSLATION' && event.locale === this.localeCode) { - this.updateData(true); - } - }); + ).subscribe(() => this.updateData(true)); this.initSubscriptions(); this.newKey = this.fb.group({ diff --git a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts index 0056c82f1a..db958cd901 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-translation/translation-table.component.ts @@ -75,13 +75,9 @@ export class TranslationTableComponent extends PageComponent implements OnInit, this.sort.active = this.pageLink.sortOrder.property; this.sort.direction = (this.pageLink.sortOrder.direction).toLowerCase() as SortDirection; this.dataSource.loadTranslateInfo(this.pageLink); - this.aiAssistantPanelService.customizationSaved$.pipe( + this.aiAssistantPanelService.customizationReload$('TRANSLATION').pipe( takeUntil(this.destroy$) - ).subscribe(event => { - if (event.kind === 'TRANSLATION') { - this.updateData(true); - } - }); + ).subscribe(() => this.updateData(true)); this.textSearch.valueChanges.pipe( debounceTime(150), distinctUntilChanged((prev, current) => (this.pageLink.textSearch ?? '') === current.trim()), diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts index 577cc8460a..75730a2d09 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts @@ -25,7 +25,6 @@ import { DashboardUtilsService } from '@core/services/dashboard-utils.service'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DashboardFormComponent } from '@home/pages/dashboard/dashboard-form.component'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { Operation, Resource } from '@shared/models/security.models'; import { ImportExportService } from '@shared/import-export/import-export.service'; import { Router, UrlTree } from '@angular/router'; @@ -147,17 +146,7 @@ export class DashboardGroupConfigFactory implements EntityGroupStateConfigFactor onAction: ($event) => this.importDashboard($event, config) } ); - if (getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { - config.headerActionDescriptors.push( - { - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.generateWithAi($event, config, params) - } - ); - } + config.headerActionDescriptors.push(...this.aiAssistantConfigService.configureAction($event => this.generateWithAi($event, config, params))); } config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(AiAssistantViewType.DASHBOARD_GROUP, undefined, config.entityGroup.id); return this.groupConfigTableConfigService.prepareConfiguration(params, config); diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts index 8a2d0c1937..e7802ec29b 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts @@ -2,7 +2,8 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { AiAssistantViewType } from '@shared/models/ai-chat.models'; -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { @@ -21,7 +22,7 @@ import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared import { EntityAction } from '@home/models/entity/entity-component.models'; import { Observable, of } from 'rxjs'; import { Store } from '@ngrx/store'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { map, mergeMap } from 'rxjs/operators'; import { AppState } from '@core/core.state'; import { Authority } from '@app/shared/models/authority.enum'; @@ -47,12 +48,13 @@ import { } from '@home/components/alias/entity-aliases-dialog.component'; import { MatDialog } from '@angular/material/dialog'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { DashboardUtilsService } from '@core/services/dashboard-utils.service'; @Injectable() export class DashboardsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private allEntitiesTableConfigService: AllEntitiesTableConfigService, private store: Store, private userPermissionsService: UserPermissionsService, @@ -99,7 +101,7 @@ export class DashboardsTableConfigResolver { config.tableTitle = this.translate.instant('dashboard.dashboards'); } config.columns = this.configureColumns(authUser, config); - if (getCurrentAuthState(this.store).aiEnabled && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { + if (this.userPermissionsService.isAiAvailable()) { config.aiAssistantConfig = { view: {listView: AiAssistantViewType.DASHBOARD_LIST, entityView: AiAssistantViewType.DASHBOARD}, initialPromptPlaceholder: this.translate.instant('dashboard.ai-assistant-initial-prompt-placeholder') @@ -215,15 +217,7 @@ export class DashboardsTableConfigResolver { onAction: ($event) => this.importDashboard($event, config) } ]; - if (getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { - actions.push({ - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.generateWithAi($event, config) - }); - } + actions.push(...this.aiAssistantConfigService.configureAction($event => this.generateWithAi($event, config))); return actions; } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss index 753e355875..71d9071d98 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/_home-table.scss @@ -110,12 +110,3 @@ text-decoration: underline; } } - -.tb-home-sr-only { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; -} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts index e84ccfb078..553a937a98 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-assistant-home.component.ts @@ -7,7 +7,6 @@ import { computed, DestroyRef, ElementRef, - HostListener, inject, Renderer2, signal, @@ -113,7 +112,7 @@ export class AiAssistantHomeComponent implements AfterViewInit { hint: true, title: this.translate.instant('home.ai.offer-title'), text: escapeTourText(this.translate.instant('home.ai.offer-text')), - foot: keyboard ? `/ ${escapeTourText(this.translate.instant('home.ai.offer-key'))}` : null, + foot: keyboard ? escapeTourText(this.translate.instant('home.ai.offer-key', {key: '\u0000'})).replace('\u0000', '/') : null, nextLabel: this.translate.instant('home.ai.offer-action'), onNext: () => this.closeOffer(true), onClose: () => this.closeOffer(false), @@ -142,14 +141,4 @@ export class AiAssistantHomeComponent implements AfterViewInit { this.panelService.handOff(prompt); this.router.navigateByUrl('/ai-assistant'); } - - @HostListener('document:keydown', ['$event']) - onSlash(event: KeyboardEvent): void { - if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented || this.dialog.openDialogs.length - || (event.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable]')) { - return; - } - event.preventDefault(); - this.composer?.focus(); - } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts index e7281e0394..a0a6f62812 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/ai-start-home.component.ts @@ -1,15 +1,14 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, NgZone, signal } from '@angular/core'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, signal } from '@angular/core'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; import { AiChatsService } from '@core/services/ai-chats.service'; import { AiSolutionsService } from '@core/services/ai-solutions.service'; -import { EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; import { EntityType } from '@shared/models/entity-type.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { NEW_SOLUTION_ID } from '@shared/models/solution-creator.models'; @Component({ @@ -80,13 +79,7 @@ export class AiStartHomeComponent { constructor() { this.chats.ensureLoaded(); this.solutions.ensureLoaded(); - const cmd = new EntityCountCmd(); - cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType: EntityType.DEVICE}}; - const subscriber = new TelemetrySubscriber(inject(TelemetryWebsocketService), inject(NgZone)); - subscriber.subscriptionCommands.push(cmd); - subscriber.entityCount$.subscribe(update => this.devices.set(update.count ?? 0)); - subscriber.subscribe(); - inject(DestroyRef).onDestroy(() => subscriber.unsubscribe()); + inject(HomeCountService).watchEntityCount(EntityType.DEVICE, count => this.devices.set(count), inject(DestroyRef)); effect(() => { if (this.resolved()) { this.writeShown(this.show()); @@ -95,18 +88,10 @@ export class AiStartHomeComponent { } private readShown(): boolean { - try { - return localStorage.getItem(this.shownKey) === '1'; - } catch { - return false; - } + return readStored(this.shownKey) === '1'; } private writeShown(shown: boolean): void { - try { - localStorage.setItem(this.shownKey, shown ? '1' : '0'); - } catch { - return; - } + writeStored(this.shownKey, shown ? '1' : '0'); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html index 851c5e1ea8..bd9aec8262 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.html @@ -22,7 +22,7 @@ @@ -34,7 +34,7 @@ } @else if (emptyState() === 'clear') {
    - {{ 'home.alarms.no-active' | translate }} {{ 'home.alarms.view-cleared' | translate }} + {{ 'home.alarms.none-active' | translate }} {{ 'home.alarms.view-cleared' | translate }}
    } @else if (total()) {
    diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts index 70c3cd0a8d..a023778112 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/alarms-home.component.ts @@ -22,9 +22,8 @@ import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service' import { AlarmService } from '@core/http/alarm.service'; import { DialogService } from '@core/services/dialog.service'; import { ToastNotificationService } from '@core/services/toast-notification.service'; -import { AlarmCountCmd, AlarmDataCmd, EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AlarmCountCmd, AlarmDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; import { AlarmRulesService } from '@core/http/alarm-rules.service'; -import { AliasFilterType } from '@shared/models/alias.models'; import { PageLink } from '@shared/models/page/page-link'; import { HelpLinks } from '@shared/models/constants'; import { catchError, of } from 'rxjs'; @@ -37,10 +36,12 @@ import { HomeCardId } from '@shared/models/user-settings.models'; import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; import { AlarmDetailsDialogComponent, AlarmDetailsDialogData } from '@home/components/alarm/alarm-details-dialog.component'; -import { homeAgo, homeListPageSize, homeListShown } from '@home/pages/home-page/home-list.models'; +import { homeAgo, homeListPageSize, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { MINUTE } from '@shared/models/time/time.models'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; -const MINUTE = 60000; const MINE_KEY = 'tb-home-alarms-mine'; const SEVERITIES = [AlarmSeverity.CRITICAL, AlarmSeverity.MAJOR, AlarmSeverity.MINOR, AlarmSeverity.WARNING]; @@ -63,23 +64,11 @@ export interface AlarmHomeRow { } const readMine = (): boolean => { - try { - return localStorage.getItem(MINE_KEY) === '1'; - } catch { - return false; - } + return readStored(MINE_KEY) === '1'; }; const writeMine = (mine: boolean): void => { - try { - if (mine) { - localStorage.setItem(MINE_KEY, '1'); - } else { - localStorage.removeItem(MINE_KEY); - } - } catch { - return; - } + writeStored(MINE_KEY, mine ? '1' : null); }; @Component({ @@ -109,6 +98,8 @@ export class AlarmsHomeComponent { private translate = inject(TranslateService); private alarmRulesService = inject(AlarmRulesService); private permissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); private readonly authUser = getCurrentAuthUser(this.store); private readonly userId = this.authUser?.userId; @@ -139,7 +130,6 @@ export class AlarmsHomeComponent { return this.devices() ? 'clear' : 'devices'; }); - private devicesSubscriber: TelemetrySubscriber | null = null; private readonly severityCounts = new Map>( SEVERITIES.map(severity => [severity, signal(null)]) ); @@ -206,7 +196,7 @@ export class AlarmsHomeComponent { constructor() { this.totalSubscriber = this.subscribeCount(this.total); if (this.canReadDevices) { - this.devicesSubscriber = this.subscribeDevices(); + this.homeCounts.watchEntityCount(EntityType.DEVICE, count => this.devices.set(count), this.destroyRef); } else { this.devices.set(1); } @@ -226,10 +216,9 @@ export class AlarmsHomeComponent { untracked(() => this.subscribeAlarms(pageLink)); }); const tick = setInterval(() => this.now.set(Date.now()), MINUTE); - inject(DestroyRef).onDestroy(() => { + this.destroyRef.onDestroy(() => { clearInterval(tick); this.totalSubscriber?.unsubscribe(); - this.devicesSubscriber?.unsubscribe(); this.severitySubscribers.forEach(subscriber => subscriber.unsubscribe()); this.dataSubscriber?.unsubscribe(); }); @@ -384,16 +373,6 @@ export class AlarmsHomeComponent { return subscriber; } - private subscribeDevices(): TelemetrySubscriber { - const cmd = new EntityCountCmd(); - cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType: EntityType.DEVICE}}; - const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); - subscriber.subscriptionCommands.push(cmd); - subscriber.entityCount$.subscribe(update => this.devices.set(update.count ?? 0)); - subscriber.subscribe(); - return subscriber; - } - private refresh(): void { this.subscribeAlarms(this.pageLink()); this.totalSubscriber?.unsubscribe(); @@ -409,14 +388,7 @@ export class AlarmsHomeComponent { } private notify(key: string, row: AlarmHomeRow): void { - this.toast.dispatchNotification({ - message: this.translate.instant(key, {name: this.alarmName(row)}), - type: 'info', - duration: 4000, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast' - }); + this.toast.dispatchNotification(homeToast(this.translate.instant(key, {name: this.alarmName(row)}))); } private alarmName(row: AlarmHomeRow): string { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html index 514e849c78..e11e8e8e79 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.html @@ -27,7 +27,7 @@ @if (canUseIotHub) { {{ 'home.dashboards.from-template' | translate }} } - {{ 'home.dashboards.how-to' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }} + {{ 'home.dashboards.how-to' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }}
    } @else { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts index 725d1ee73b..54925fa96e 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/dashboards-home.component.ts @@ -20,12 +20,12 @@ import { PageLink } from '@shared/models/page/page-link'; import { Direction } from '@shared/models/page/sort-order'; import { HomeCardId, UserDashboardAction, UserDashboardsInfo } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; -import { homeAgo, homeListShown } from '@home/pages/home-page/home-list.models'; +import { homeAgo, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; +import { MINUTE } from '@shared/models/time/time.models'; import { HomeToggleOption } from '@home/pages/home-page/components/home-toggle.component'; type DashboardsTab = 'last' | 'starred'; -const MINUTE = 60000; const SEARCH_SIZE = 10; const FILL_SIZE = 20; @@ -249,14 +249,7 @@ export class DashboardsHomeComponent { pick(candidate: StarCandidate): void { this.closePicker(); this.star(candidate.id, candidate.title); - this.toast.dispatchNotification({ - message: this.translate.instant('home.dashboards.starred-toast', {title: candidate.title}), - type: 'info', - duration: 4000, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast' - }); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.dashboards.starred-toast', {title: candidate.title}))); } private star(id: string, title: string): void { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts index e71097f755..b34021b089 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-activity-home.component.ts @@ -25,7 +25,7 @@ import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service' import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; import { AliasFilterType } from '@shared/models/alias.models'; import { EntityKeyType } from '@shared/models/query/query.models'; -import { AggregationType } from '@shared/models/time/time.models'; +import { AggregationType, DAY } from '@shared/models/time/time.models'; import { HomeCardId } from '@shared/models/user-settings.models'; import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; @@ -34,7 +34,6 @@ import { homeChartHoverSymbol, homeChartTooltipHtml, homeChartTooltipOptions } f type ActivitySeries = 'devices' | 'messages'; -const DAY = 86400000; const DAYS = 30; const LABEL_STEP = 7; const SCALE_STEPS = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html index 680019a649..cfc7ac383b 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.html @@ -20,7 +20,7 @@ } @else { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts index 036fb27ea5..fb68fc1bd8 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/devices-home.component.ts @@ -20,7 +20,7 @@ import { AppState } from '@core/core.state'; import { selectPersistDeviceStateToTelemetry } from '@core/auth/auth.selectors'; import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; import { HomePermissionsService } from '@home/pages/home-page/home-permissions.service'; -import { EntityCountCmd, EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; import { AliasFilterType } from '@shared/models/alias.models'; import { EntityType } from '@shared/models/entity-type.models'; import { @@ -38,13 +38,13 @@ import { Direction } from '@shared/models/page/sort-order'; import { HelpLinks } from '@shared/models/constants'; import { HomeCardId } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { MINUTE } from '@shared/models/time/time.models'; import { homeAgo, homeListPageSize, homeListShown } from '@home/pages/home-page/home-list.models'; type DeviceState = 'inactive' | 'active'; type DeviceSortKey = 'last' | 'name'; -const MINUTE = 60000; - interface DeviceQuery { state: DeviceState | null; sortKey: EntityKey; @@ -89,6 +89,8 @@ export class DevicesHomeComponent { private router = inject(Router); private translate = inject(TranslateService); private permissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); readonly canAdd = this.permissions.canReadAllEntities(EntityType.DEVICE) && this.permissions.canCreateEntities(EntityType.DEVICE); readonly devicesLink = this.permissions.entitiesLink(EntityType.DEVICE); @@ -107,7 +109,6 @@ export class DevicesHomeComponent { private readonly listTotals = signal([]); private readonly now = signal(Date.now()); - private countSubscribers: TelemetrySubscriber[] = []; private dataSubscribers: TelemetrySubscriber[] = []; readonly tiles = computed(() => { @@ -172,11 +173,9 @@ export class DevicesHomeComponent { constructor() { this.store.select(selectPersistDeviceStateToTelemetry).pipe(take(1)).subscribe(persisted => { const keyType = persisted ? EntityKeyType.TIME_SERIES : EntityKeyType.SERVER_ATTRIBUTE; - this.countSubscribers = [ - this.subscribeCount(this.total), - this.subscribeCount(this.inactive, this.activeFilter(keyType, false)), - this.subscribeCount(this.active, this.activeFilter(keyType, true)) - ]; + this.subscribeCount(this.total); + this.subscribeCount(this.inactive, this.activeFilter(keyType, false)); + this.subscribeCount(this.active, this.activeFilter(keyType, true)); this.stateKeyType.set(keyType); }); effect(() => { @@ -187,7 +186,6 @@ export class DevicesHomeComponent { const tick = setInterval(() => this.now.set(Date.now()), MINUTE); inject(DestroyRef).onDestroy(() => { clearInterval(tick); - this.countSubscribers.forEach(subscriber => subscriber.unsubscribe()); this.dataSubscribers.forEach(subscriber => subscriber.unsubscribe()); }); } @@ -300,17 +298,8 @@ export class DevicesHomeComponent { return {...current, latest}; } - private subscribeCount(target: WritableSignal, keyFilters?: KeyFilter[]): TelemetrySubscriber { - const cmd = new EntityCountCmd(); - cmd.query = { - entityFilter: {type: AliasFilterType.entityType, entityType: EntityType.DEVICE}, - keyFilters - }; - const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); - subscriber.subscriptionCommands.push(cmd); - subscriber.entityCount$.subscribe(update => target.set(update.count ?? 0)); - subscriber.subscribe(); - return subscriber; + private subscribeCount(target: WritableSignal, keyFilters?: KeyFilter[]): void { + this.homeCounts.watchEntityCount(EntityType.DEVICE, count => target.set(count), this.destroyRef, keyFilters); } private activeFilter(keyType: EntityKeyType, active: boolean): KeyFilter[] { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html index a800660b4a..c7f1cb015a 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.html @@ -31,7 +31,7 @@ {{ 'home.get-started.' + step.key + '.title' | translate }}

    {{ 'home.get-started.' + step.key + '.text' | translate }} - {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }} + {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }}

    @if (step.code) {
    {{ step.code }}
    diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss index a14f60fbd4..c2b73ddfeb 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.scss @@ -200,12 +200,6 @@ li.done:not(.open) .tb-gs-title { } .tb-gs-open.mat-mdc-outlined-button { - --mdc-outlined-button-container-height: 32px; - --mat-outlined-button-container-height: 32px; - --mdc-outlined-button-outline-color: rgba(0, 0, 0, 0.1); - --mat-outlined-button-outline-color: rgba(0, 0, 0, 0.1); - --mdc-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mat-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); height: 32px; padding: 0 16px; border-radius: 4px; @@ -217,8 +211,6 @@ li.done:not(.open) .tb-gs-title { } .tb-gs-done.mat-mdc-button, .tb-gs-again .mat-mdc-button { - --mdc-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mat-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); height: 32px; padding: 0 8px; @@ -269,8 +261,6 @@ li.done:not(.open) .tb-gs-title { } .tb-gs-open.mat-mdc-outlined-button, .tb-gs-done.mat-mdc-button { - --mdc-outlined-button-container-height: 36px; - --mat-outlined-button-container-height: 36px; height: 36px; } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts index fed259b9f3..7628503b41 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-home.component.ts @@ -20,6 +20,7 @@ import { ToastNotificationService } from '@core/services/toast-notification.serv import { baseUrl } from '@core/utils'; import { GettingStarted, HomeCardId } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; export interface GetStartedStep { @@ -30,8 +31,6 @@ export interface GetStartedStep { code?: string; } -const UNDO_MS = 6000; - const sendCommand = (temperature: number): string => `curl -X POST ${baseUrl()}/api/v1/$ACCESS_TOKEN/telemetry \\\n -H "Content-Type: application/json" \\\n -d '{"temperature": ${temperature}}'`; @@ -128,16 +127,10 @@ export class GetStartedHomeComponent { startOver(): void { const before = this.settings(); this.save({lastSelectedIndex: 0, maxSelectedIndex: 0}); - this.toast.dispatchNotification({ - message: this.translate.instant('home.get-started.started-over'), - type: 'info', - duration: UNDO_MS, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast', - actionLabel: this.translate.instant('home.customize.undo'), - onAction: () => this.save(before) - }); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.get-started.started-over'), { + label: this.translate.instant('home.customize.undo'), + action: () => this.save(before) + })); } private save(settings: GettingStarted): void { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html index a26a4f1c6d..b48969c846 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.html @@ -49,7 +49,7 @@ {{ 'home.get-started-sys-admin.' + step.key + '.title' | translate }}

    {{ 'home.get-started-sys-admin.' + step.key + '.text' | translate }} - {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }} + {{ 'home.get-started.guide' | translate }}{{ 'home.dashboards.opens-new-tab' | translate }}

    @if (stepState === 'done') { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss index c178db33f5..ac4775be5b 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.scss @@ -208,18 +208,10 @@ li.done:not(.open) .tb-sgs-title { } .tb-sgs-action.mat-mdc-outlined-button { - --mdc-outlined-button-outline-color: rgba(0, 0, 0, 0.1); - --mat-outlined-button-outline-color: rgba(0, 0, 0, 0.1); - --mdc-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mat-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); background: #fff; } .tb-sgs-skip.mat-mdc-button, .tb-sgs-close.mat-mdc-outlined-button { - --mdc-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mat-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mdc-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mat-outlined-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); height: 32px; } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts index 3d64af7183..a96d059529 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/get-started-sys-admin-home.component.ts @@ -7,7 +7,6 @@ import { DestroyRef, ElementRef, inject, - NgZone, signal } from '@angular/core'; import { Store } from '@ngrx/store'; @@ -18,13 +17,12 @@ import { AppState } from '@core/core.state'; import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; import { UserSettingsService } from '@core/http/user-settings.service'; import { WhiteLabelingService } from '@core/http/white-labeling.service'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; import { EntityType } from '@shared/models/entity-type.models'; import { FeaturesInfo } from '@shared/models/settings.models'; import { HomeCardId } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; type SysAdminStepKey = 'tenant' | 'email' | 'sms' | 'wl' | '2fa' | 'oauth' | 'slack'; @@ -53,11 +51,7 @@ const LOADING_HEIGHT = 398; const HEIGHT_KEY = 'tb-home-get-started-sys-admin-height'; const storedHeight = (): number => { - try { - return Number(localStorage.getItem(HEIGHT_KEY)) || LOADING_HEIGHT; - } catch { - return LOADING_HEIGHT; - } + return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT; }; export type StepState = 'done' | 'skipped' | 'todo'; @@ -131,17 +125,12 @@ export class GetStartedSysAdminHomeComponent { inject(SysAdminHomeService).featuresInfo$.subscribe(features => this.features.set(features ?? {} as FeaturesInfo)); this.userSettingsService.getGettingStarted(config).pipe(catchError(() => of(null))) .subscribe(settings => this.skipped.set(settings?.skipped ?? [])); - const cmd = new EntityCountCmd(); - cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType: EntityType.TENANT}}; - const subscriber = new TelemetrySubscriber(inject(TelemetryWebsocketService), inject(NgZone)); - subscriber.subscriptionCommands.push(cmd); - subscriber.entityCount$.subscribe(update => this.tenants.set(update.count ?? 0)); - subscriber.subscribe(); + const destroyRef = inject(DestroyRef); + inject(HomeCountService).watchEntityCount(EntityType.TENANT, count => this.tenants.set(count), destroyRef); const host = inject>(ElementRef); const observer = new ResizeObserver(() => this.rememberHeight(host.nativeElement)); observer.observe(host.nativeElement); - inject(DestroyRef).onDestroy(() => { - subscriber.unsubscribe(); + destroyRef.onDestroy(() => { observer.disconnect(); }); } @@ -175,11 +164,7 @@ export class GetStartedSysAdminHomeComponent { if (!this.loaded() || !height) { return; } - try { - localStorage.setItem(HEIGHT_KEY, String(height)); - } catch { - return; - } + writeStored(HEIGHT_KEY, String(height)); } close(): void { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts index 3be22a00b5..c970bf9efa 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-card.component.ts @@ -6,10 +6,9 @@ import { ToastNotificationService } from '@core/services/toast-notification.serv import { TranslateService } from '@ngx-translate/core'; import { AppState } from '@core/core.state'; import { ActionPreferencesUpdateHomeCards } from '@core/auth/auth.actions'; +import { homeToast } from '@home/pages/home-page/home-list.models'; import { HomeCardDefinition } from '@home/pages/home-page/home-cards.models'; -const UNDO_MS = 6000; - @Component({ selector: 'tb-home-card', template: ` @@ -74,15 +73,9 @@ export class HomeCardComponent { const id = this.card().id; const name = this.translate.instant(this.card().name); this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: false})); - this.toast.dispatchNotification({ - message: this.translate.instant('home.customize.hidden', {name}), - type: 'info', - duration: UNDO_MS, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast', - actionLabel: this.translate.instant('home.customize.undo'), - onAction: () => this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: true})) - }); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.customize.hidden', {name}), { + label: this.translate.instant('home.customize.undo'), + action: () => this.store.dispatch(new ActionPreferencesUpdateHomeCards({[id]: true})) + })); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss index d160ff6edc..76b917af59 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/home-toast.scss @@ -26,7 +26,6 @@ .tb-toast .mat-mdc-button.mat-mdc-button-base.mat-mdc-button-base { --mat-button-text-label-text-color: rgba(255, 255, 255, 0.92); - --mdc-text-button-label-text-color: rgba(255, 255, 255, 0.92); flex: none; min-width: 0; height: 32px; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html index a31b26a71f..ce5c790bac 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.html @@ -39,7 +39,7 @@ [matTooltip]="(feature.on === null ? 'home.install.checking' : feature.on ? 'widgets.configured-features.feature-configured' : 'widgets.configured-features.feature-not-configured') | translate"> {{ feature.on ? 'check_circle' : 'radio_button_unchecked' }} {{ feature.label | translate }} - {{ (feature.on === null ? 'home.install.checking' : feature.on ? 'home.install.configured' : 'home.install.not-configured') | translate }} + {{ (feature.on === null ? 'home.install.checking' : feature.on ? 'home.install.configured' : 'home.install.not-configured') | translate }} }
    diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts index f45ef7891d..1420b32d6b 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/install-items-home.component.ts @@ -1,13 +1,11 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, NgZone, signal, WritableSignal } from '@angular/core'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, signal, WritableSignal } from '@angular/core'; import { EntityType } from '@shared/models/entity-type.models'; import { FeaturesInfo } from '@shared/models/settings.models'; import { HomeCardId } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; interface InstallCount { @@ -67,17 +65,8 @@ export class InstallItemsHomeComponent { constructor() { inject(SysAdminHomeService).featuresInfo$.subscribe(info => this.featuresInfo.set(info)); - const telemetryWsService = inject(TelemetryWebsocketService); - const zone = inject(NgZone); - const subscribers = this.counts.map(item => { - const cmd = new EntityCountCmd(); - cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType: item.entityType}}; - const subscriber = new TelemetrySubscriber(telemetryWsService, zone); - subscriber.subscriptionCommands.push(cmd); - subscriber.entityCount$.subscribe(update => item.count.set(update.count ?? 0)); - subscriber.subscribe(); - return subscriber; - }); - inject(DestroyRef).onDestroy(() => subscribers.forEach(subscriber => subscriber.unsubscribe())); + const homeCounts = inject(HomeCountService); + const destroyRef = inject(DestroyRef); + this.counts.forEach(item => homeCounts.watchEntityCount(item.entityType, count => item.count.set(count), destroyRef)); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts index b697eb2b0c..5e5be732b8 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/iot-hub-home.component.ts @@ -11,6 +11,7 @@ import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { writeStored } from '@core/local-storage/stored'; import { PageLink } from '@shared/models/page/page-link'; const SHOWN = 8; @@ -44,11 +45,7 @@ const readSnapshot = (): HubSnapshot | null => { const writeSnapshot = (snapshot: HubSnapshot): void => { lastSnapshot = snapshot; - try { - localStorage.setItem(CACHE_KEY, JSON.stringify(snapshot)); - } catch { - return; - } + writeStored(CACHE_KEY, JSON.stringify(snapshot)); }; const TEMPLATE_TINTS = ['#e0f2f1,#80cbc4', '#e3f2fd,#90caf9', '#fff3e0,#ffcc80', '#f3e5f5,#ce93d8', '#e8f5e9,#a5d6a7', diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html index 6e70b7d735..97a8d74549 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.html @@ -62,7 +62,7 @@ {{ row.used | shortNumber: {roundDown: true} }} / {{ row.max | shortNumber: {roundDown: true} }} @if (row.tone) { - {{ (row.tone === 'critical' ? 'home.license.at-limit' : 'home.license.of-limit') | translate: {percent: row.percent} }} + {{ (row.tone === 'critical' ? 'home.license.at-limit' : 'home.license.of-limit') | translate: {percent: row.percent} }} } } @else { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss index 0d70fe1629..af4b9821e7 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.scss @@ -6,15 +6,6 @@ container: tb-license / inline-size; } -.tb-home-sr-only { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; -} - .tb-license-updated { display: inline-flex; align-items: center; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts index 05582f95df..a5aa2f231d 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/license-home.component.ts @@ -19,6 +19,7 @@ import { usageItemTypeTranslationMap } from '@shared/models/subscription.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { LicenseActionsService, licenseLimitCritical, @@ -30,11 +31,7 @@ const LOADING_HEIGHT = 398; const HEIGHT_KEY = 'tb-home-license-height'; const storedHeight = (): number => { - try { - return Number(localStorage.getItem(HEIGHT_KEY)) || LOADING_HEIGHT; - } catch { - return LOADING_HEIGHT; - } + return Number(readStored(HEIGHT_KEY)) || LOADING_HEIGHT; }; const AGO_REFRESH_MS = 30_000; @@ -274,11 +271,7 @@ export class LicenseHomeComponent { if (!this.info() || !height) { return; } - try { - localStorage.setItem(HEIGHT_KEY, String(height)); - } catch { - return; - } + writeStored(HEIGHT_KEY, String(height)); } private limit(info: SubscriptionInfo, itemType: UsageItemType, used: number, max: number, addEnabled: boolean, diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts index 6e00b0f22c..c3edd35416 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/notifications-home.component.ts @@ -18,17 +18,17 @@ import { TranslateService } from '@ngx-translate/core'; import { filter } from 'rxjs/operators'; import { HomeCardId } from '@shared/models/user-settings.models'; import { HOME_CARDS } from '@home/pages/home-page/home-cards.models'; -import { homeAgo, homeListShown } from '@home/pages/home-page/home-list.models'; +import { homeAgo, homeListShown, homeToast } from '@home/pages/home-page/home-list.models'; import { NotificationWebsocketService } from '@core/ws/notification-websocket.service'; import { NotificationSubscriber } from '@shared/models/telemetry/telemetry.models'; import { ActionButtonLinkType, Notification, NotificationType, NotificationTypeIcons } from '@shared/models/notification.models'; import { UtilsService } from '@core/services/utils.service'; import { ToastNotificationService } from '@core/services/toast-notification.service'; import { StateObject } from '@core/api/widget-api.models'; +import { MINUTE } from '@shared/models/time/time.models'; import { objToBase64URI } from '@core/utils'; const LIMIT = 10; -const MINUTE = 60000; interface NotificationHomeRow { id: string; @@ -218,13 +218,6 @@ export class NotificationsHomeComponent { } private notify(message: string): void { - this.toast.dispatchNotification({ - message, - type: 'info', - duration: 4000, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast' - }); + this.toast.dispatchNotification(homeToast(message)); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts index 60ccbe60d3..9d84d330e0 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/product-release-home.component.ts @@ -4,10 +4,9 @@ import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@a import { TranslateService } from '@ngx-translate/core'; import { ToastNotificationService } from '@core/services/toast-notification.service'; import { UpdateMessage } from '@shared/models/settings.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; import { SysAdminHomeService } from '@home/pages/home-page/sys-admin-home.service'; -const UNDO_MS = 6000; - @Component({ selector: 'tb-product-release-home', templateUrl: './product-release-home.component.html', @@ -35,15 +34,9 @@ export class ProductReleaseHomeComponent { hide(): void { const version = this.update().latestVersion; this.sysAdminHome.setHiddenRelease(version); - this.toast.dispatchNotification({ - message: this.translate.instant('home.release.hidden', {version}), - type: 'info', - duration: UNDO_MS, - horizontalPosition: 'right', - verticalPosition: 'bottom', - panelClass: 'tb-home-toast', - actionLabel: this.translate.instant('home.customize.undo'), - onAction: () => this.sysAdminHome.setHiddenRelease(null) - }); + this.toast.dispatchNotification(homeToast(this.translate.instant('home.release.hidden', {version}), { + label: this.translate.instant('home.customize.undo'), + action: () => this.sysAdminHome.setHiddenRelease(null) + })); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss index 69011faae1..332d8ce52a 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-link-dialog.component.scss @@ -400,7 +400,6 @@ .mat-mdc-button { --mat-button-text-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mdc-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html index f341630f4a..9c0fb707dc 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.html @@ -73,7 +73,7 @@ {{ link.icon }} {{ link.name }} - {{ 'home.quick-links.opens-new-tab' | translate }} + {{ 'home.quick-links.opens-new-tab' | translate }} } } @empty { diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss index 62e65b4237..370e29baf9 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.scss @@ -255,7 +255,6 @@ .mat-mdc-button { --mat-button-text-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); - --mdc-text-button-label-text-color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); margin-left: -8px; color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts index 39be0561f8..7000b2d253 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/quick-links-home.component.ts @@ -38,6 +38,7 @@ import { QuickLinkView, quickWebLinkId } from '@home/pages/home-page/quick-links.models'; +import { homeToast } from '@home/pages/home-page/home-list.models'; import { QuickLinkDialogComponent, QuickLinkDialogData @@ -217,13 +218,6 @@ export class QuickLinksHomeComponent { } private toastConfig(message: string) { - return { - message, - type: 'info' as const, - duration: 4000, - horizontalPosition: 'right' as const, - verticalPosition: 'bottom' as const, - panelClass: 'tb-home-toast' - }; + return homeToast(message); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts index e7fd12d732..896074e584 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/status-line-home.component.ts @@ -6,7 +6,7 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthUser, selectPersistDeviceStateToTelemetry } from '@core/auth/auth.selectors'; import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { AlarmCountCmd, EntityCountCmd, EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AlarmCountCmd, EntityDataCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; import { AliasFilterType } from '@shared/models/alias.models'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityKeyType, EntityKeyValueType, FilterPredicateType, BooleanOperation, KeyFilter } from '@shared/models/query/query.models'; @@ -20,6 +20,8 @@ import { TranslateService } from '@ngx-translate/core'; import { FeaturesInfo } from '@shared/models/settings.models'; import { SubscriptionInfo } from '@shared/models/subscription.models'; import { of } from 'rxjs'; +import { HomeCountService } from '@home/pages/home-page/home-count.service'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { catchError, take } from 'rxjs/operators'; type StatusKind = 'crit' | 'warn' | 'ok'; @@ -98,6 +100,8 @@ export class StatusLineHomeComponent { private readonly customer = this.authority === Authority.CUSTOMER_USER; readonly sysAdmin = this.authority === Authority.SYS_ADMIN; private readonly homePermissions = inject(HomePermissionsService); + private homeCounts = inject(HomeCountService); + private destroyRef = inject(DestroyRef); private readonly canReadAlarms = !this.sysAdmin && this.homePermissions.canReadAlarms(); private readonly canReadDevices = !this.sysAdmin && this.homePermissions.canReadEntities(EntityType.DEVICE); private readonly devicesLink = this.canReadDevices ? this.homePermissions.entitiesLink(EntityType.DEVICE) : null; @@ -217,7 +221,7 @@ export class StatusLineHomeComponent { } constructor() { - inject(DestroyRef).onDestroy(() => this.subscribers.forEach(subscriber => subscriber.unsubscribe())); + this.destroyRef.onDestroy(() => this.subscribers.forEach(subscriber => subscriber.unsubscribe())); effect(() => { if (this.resolved()) { this.rememberShown(this.parts().length > 0); @@ -254,19 +258,11 @@ export class StatusLineHomeComponent { } private wasShown(): boolean { - try { - return localStorage.getItem(this.shownKey) === '1'; - } catch { - return false; - } + return readStored(this.shownKey) === '1'; } private rememberShown(shown: boolean): void { - try { - localStorage.setItem(this.shownKey, shown ? '1' : '0'); - } catch { - return; - } + writeStored(this.shownKey, shown ? '1' : '0'); } open(part: StatusPart): void { @@ -355,17 +351,10 @@ export class StatusLineHomeComponent { } private countEntities(target: WritableSignal, entityType: EntityType, keyFilters?: KeyFilter[]): void { - const cmd = new EntityCountCmd(); - cmd.query = { - entityFilter: {type: AliasFilterType.entityType, entityType}, - keyFilters - }; - const subscriber = this.subscribe(cmd); - subscriber.entityCount$.subscribe(update => target.set(update.count ?? 0)); - subscriber.subscribe(); + this.homeCounts.watchEntityCount(entityType, count => target.set(count), this.destroyRef, keyFilters); } - private subscribe(cmd: AlarmCountCmd | EntityCountCmd): TelemetrySubscriber { + private subscribe(cmd: AlarmCountCmd): TelemetrySubscriber { const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); subscriber.subscriptionCommands.push(cmd); this.subscribers.push(subscriber); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts index 49ab7166a0..7f6ef72e8f 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/system-status-home.component.ts @@ -20,7 +20,7 @@ import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service' import { EntityDataCmd, IntervalType, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; import { AliasFilterType } from '@shared/models/alias.models'; import { EntityKeyType } from '@shared/models/query/query.models'; -import { AggregationType } from '@shared/models/time/time.models'; +import { AggregationType, HOUR, MINUTE } from '@shared/models/time/time.models'; import { UpdateMessage } from '@shared/models/settings.models'; import { HomeCardId } from '@shared/models/user-settings.models'; import { ECharts, echartsModule, EChartsOption } from '@home/components/widget/lib/chart/echarts-widget.models'; @@ -65,8 +65,6 @@ const METRICS: MetricConfig[] = [ const SERVICE_KEYS: Record = {cpu: 'cpuUsage', ram: 'memoryUsage', disk: 'discUsage'}; const LATEST_KEYS = ['clusterMode', 'clusterSystemData', 'cpuUsage', 'cpuCount', 'memoryUsage', 'totalMemory', 'discUsage', 'totalDiscSpace']; -const HOUR = 3600000; -const MINUTE = 60000; const LABEL_STEP = 15 * MINUTE; const LOADING_HEIGHT = 304; const SERVICES_PREVIEW = 8; @@ -205,7 +203,7 @@ export class SystemStatusHomeComponent { const name = this.metricName(worst.metric); const value = Math.round(worst.value); const title = worst.services.length - ? this.translate.instant('home.system.at-on', {name, value, services: worst.services.join(this.translate.instant('home.system.and'))}) + ? this.translate.instant('home.system.at-on', {name, value, services: worst.services.reduce((first, second) => this.translate.instant('home.system.and', {first, second}))}) : this.translate.instant('home.system.at', {name, value}); return {level: worst.level, title, text: this.levelText(worst.metric, worst.level).replace(/^[^.]+\.\s*/, '')}; }); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts index 3c6bab7c89..e01fbb844d 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/components/waiting-ai-chats-home.component.ts @@ -9,6 +9,7 @@ import { homeAgo, homeElapsed } from '@home/pages/home-page/home-list.models'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { readStored, writeStored } from '@core/local-storage/stored'; import { AiChatsService } from '@core/services/ai-chats.service'; const SHOWN = 2; @@ -91,18 +92,10 @@ export class WaitingAIChatsHomeComponent { } private readShown(): number { - try { - return Math.min(SHOWN, Math.max(0, Number(localStorage.getItem(this.shownKey)) || 0)); - } catch { - return 0; - } + return Math.min(SHOWN, Math.max(0, Number(readStored(this.shownKey)) || 0)); } private writeShown(count: number): void { - try { - localStorage.setItem(this.shownKey, String(count)); - } catch { - return; - } + writeStored(this.shownKey, String(count)); } } diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts new file mode 100644 index 0000000000..13c6882eb7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-count.service.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { DestroyRef, inject, Injectable, NgZone } from '@angular/core'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { EntityCountCmd, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityType } from '@shared/models/entity-type.models'; +import { KeyFilter } from '@shared/models/query/query.models'; + +interface SharedCount { + subscriber: TelemetrySubscriber; + listeners: Set<(count: number) => void>; + last?: number; +} + +@Injectable({ + providedIn: 'root' +}) +export class HomeCountService { + + private telemetryWsService = inject(TelemetryWebsocketService); + private zone = inject(NgZone); + private counts = new Map(); + + watchEntityCount(entityType: EntityType, onCount: (count: number) => void, destroyRef: DestroyRef, keyFilters?: KeyFilter[]): () => void { + const key = JSON.stringify([entityType, keyFilters ?? null]); + let shared = this.counts.get(key); + if (!shared) { + const cmd = new EntityCountCmd(); + cmd.query = {entityFilter: {type: AliasFilterType.entityType, entityType}, keyFilters}; + const subscriber = new TelemetrySubscriber(this.telemetryWsService, this.zone); + subscriber.subscriptionCommands.push(cmd); + const created: SharedCount = {subscriber, listeners: new Set()}; + subscriber.entityCount$.subscribe(update => { + created.last = update.count ?? 0; + created.listeners.forEach(listener => listener(created.last)); + }); + subscriber.subscribe(); + this.counts.set(key, created); + shared = created; + } else if (shared.last !== undefined) { + onCount(shared.last); + } + shared.listeners.add(onCount); + let released = false; + const release = () => { + if (released) { + return; + } + released = true; + shared.listeners.delete(onCount); + if (!shared.listeners.size) { + shared.subscriber.unsubscribe(); + this.counts.delete(key); + } + }; + destroyRef.onDestroy(release); + return release; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts index a6b80ac412..7e6ee899ed 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-list.models.ts @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { TranslateService } from '@ngx-translate/core'; +import { MINUTE } from '@shared/models/time/time.models'; +import { NotificationMessage } from '@core/notification/notification.models'; export const HOME_LIST_PREVIEW = 5; export const HOME_LIST_SLACK = 2; export const HOME_LIST_LIMIT = 10; -const MINUTE = 60000; - export const homeListPageSize = (expanded: boolean): number => expanded ? HOME_LIST_LIMIT : HOME_LIST_PREVIEW + HOME_LIST_SLACK; export const homeListFew = (total: number): boolean => total <= HOME_LIST_PREVIEW + HOME_LIST_SLACK; @@ -39,3 +39,16 @@ const agoText = (translate: TranslateService, ms: number, prefix: string): strin export const homeAgo = (translate: TranslateService, ms: number): string => agoText(translate, ms, 'home.ago'); export const homeElapsed = (translate: TranslateService, ms: number): string => agoText(translate, ms, 'home.elapsed'); + +const HOME_TOAST_MS = 4000; +const HOME_UNDO_MS = 6000; + +export const homeToast = (message: string, undo?: {label: string; action: () => void}): NotificationMessage => ({ + message, + type: 'info', + duration: undo ? HOME_UNDO_MS : HOME_TOAST_MS, + horizontalPosition: 'right', + verticalPosition: 'bottom', + panelClass: 'tb-home-toast', + ...(undo ? {actionLabel: undo.label, onAction: undo.action} : {}) +}); diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss index ff9d71fb94..07b4f7061a 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.scss @@ -1,6 +1,5 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 tb-home-page.tb-home-dashboard { display: block; width: 100%; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts index b65b139df5..4db28b4d77 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.component.ts @@ -1,6 +1,5 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 import { ChangeDetectionStrategy, Component, inject, ViewEncapsulation } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Store } from '@ngrx/store'; diff --git a/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts b/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts index 83ecf431a6..a70a6ebf88 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/home-page.module.ts @@ -1,6 +1,5 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -39,7 +38,7 @@ import { GetStartedSysAdminHomeComponent } from '@home/pages/home-page/component import { SystemStatusHomeComponent } from '@home/pages/home-page/components/system-status-home.component'; import { LicenseHomeComponent } from '@home/pages/home-page/components/license-home.component'; import { InstallItemsHomeComponent } from '@home/pages/home-page/components/install-items-home.component'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiComposerModule } from '@home/components/ai/ai-composer.module'; @NgModule({ declarations: @@ -80,7 +79,7 @@ import { AiModule } from '@home/components/ai/ai.module'; CommonModule, SharedModule, HomeComponentsModule, - AiModule, + AiComposerModule, HomePageRoutingModule ] }) diff --git a/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts b/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts index a42ef7b564..dd1a57a9f3 100644 --- a/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts +++ b/ui-ngx/src/app/modules/home/pages/home-page/quick-links.models.ts @@ -4,6 +4,7 @@ import { Params } from '@angular/router'; import { Authority } from '@shared/models/authority.enum'; import { DocumentationLink, QUICK_WEB_LINK_PREFIX, QuickLinks } from '@shared/models/user-settings.models'; import { MenuSection } from '@core/services/menu.models'; +import { guid } from '@core/utils'; export const QUICK_LINKS_MAX = 12; @@ -31,7 +32,7 @@ export type QuickLinkDialogResult = {page: QuickLinkPage} | {web: DocumentationL export const isQuickWebLinkId = (id: string): boolean => id.startsWith(QUICK_WEB_LINK_PREFIX); -export const quickWebLinkId = (): string => QUICK_WEB_LINK_PREFIX + crypto.randomUUID(); +export const quickWebLinkId = (): string => QUICK_WEB_LINK_PREFIX + guid(); export const defaultQuickLinks = (authority: Authority, docsUrl: string, translate: (key: string) => string): QuickLinks => { const web = (id: string, name: string, icon: string, link: string) => ({[QUICK_WEB_LINK_PREFIX + id]: {name, icon, link}}); diff --git a/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts b/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts index 779d067ff4..9f7634a9e5 100644 --- a/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts +++ b/ui-ngx/src/app/modules/home/pages/mobile/qr-code-widget/mobile-qr-code-widget-settings.component.ts @@ -18,7 +18,7 @@ import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { ActivatedRoute } from '@angular/router'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { filter, switchMap } from 'rxjs/operators'; +import { switchMap } from 'rxjs/operators'; @Component({ selector: 'tb-mobile-qr-code-widget', @@ -60,8 +60,7 @@ export class MobileQrCodeWidgetSettingsComponent extends PageComponent implement private route: ActivatedRoute, private aiAssistantPanelService: AiAssistantPanelService) { super(store); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'MOBILE_QR_CODE' && !this.mobileAppSettingsForm.dirty), + this.aiAssistantPanelService.customizationReload$('MOBILE_QR_CODE', () => !this.mobileAppSettingsForm.dirty).pipe( switchMap(() => this.mobileAppService.getMobileAppSettings({ignoreLoading: true})), takeUntilDestroyed() ).subscribe(settings => { diff --git a/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts b/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts index d21046bc82..84f759fe67 100644 --- a/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts +++ b/ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts @@ -23,7 +23,7 @@ import { DialogService } from '@core/services/dialog.service'; import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { filter, switchMap } from 'rxjs/operators'; +import { switchMap } from 'rxjs/operators'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; @@ -61,8 +61,7 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn private aiAssistantPanelService: AiAssistantPanelService, ) { super(store); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'ACCOUNT_NOTIFICATIONS' && !this.notificationSettings?.dirty && !!this.notificationDeliveryMethods), + this.aiAssistantPanelService.customizationReload$('ACCOUNT_NOTIFICATIONS', () => !this.notificationSettings?.dirty && !!this.notificationDeliveryMethods).pipe( switchMap(() => this.notificationService.getNotificationUserSettings({ignoreLoading: true})), takeUntilDestroyed() ).subscribe(settings => this.patchNotificationSettings(settings)); diff --git a/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts b/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts index 047d9e85b3..e624653f47 100644 --- a/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts +++ b/ui-ngx/src/app/modules/home/pages/profile/profile.component.ts @@ -22,7 +22,7 @@ import { UnitService } from '@core/services/unit.service'; import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { filter, switchMap } from 'rxjs/operators'; +import { switchMap } from 'rxjs/operators'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({ @@ -51,8 +51,7 @@ export class ProfileComponent extends PageComponent implements OnInit, HasConfir private aiAssistantPanelService: AiAssistantPanelService, ) { super(store); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'PROFILE' && !this.profile?.dirty), + this.aiAssistantPanelService.customizationReload$('PROFILE', () => !this.profile?.dirty).pipe( switchMap(() => this.userService.getUser(this.user.id.id, {ignoreLoading: true})), takeUntilDestroyed() ).subscribe(user => this.userLoaded(user)); diff --git a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.ts b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.ts index d3b2555a2b..b8ea993e21 100644 --- a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template-page.component.ts @@ -75,21 +75,18 @@ import { DialogService } from '@core/services/dialog.service'; import { ReportService } from '@core/http/report.service'; import { ReportComponentsComponent } from '@home/pages/reporting/template/components/report-components.component'; import { EntityType } from '@shared/models/entity-type.models'; -import { Observable, skip, startWith, Subject } from 'rxjs'; +import { Observable, of, skip, startWith, Subject } from 'rxjs'; import { EntityAliasDialogComponent, EntityAliasDialogData } from '@home/components/alias/entity-alias-dialog.component'; -import { buffer, debounceTime, distinctUntilChanged, map, tap } from 'rxjs/operators'; +import { debounceTime, distinctUntilChanged, filter, switchMap, tap } from 'rxjs/operators'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AiAssistantViewType } from '@shared/models/ai-chat.models'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; -const AI_RELOAD_DEBOUNCE_MS = 1000; import { FilterDialogComponent, FilterDialogData } from '@home/components/filter/filter-dialog.component'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { DatePipe } from '@angular/common'; @@ -250,7 +247,7 @@ export class ReportTemplatePageComponent extends PageComponent } get aiAssistantAvailable(): boolean { - return getCurrentAuthState(this.appStore).aiEnabled && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } ngOnInit() { @@ -302,14 +299,20 @@ export class ReportTemplatePageComponent extends PageComponent } this.panelService.setEnabled(true); this.updateAiConfig(); - this.panelService.updatedData$.pipe( - buffer(this.panelService.updatedData$.pipe(debounceTime(AI_RELOAD_DEBOUNCE_MS))), - map(batches => batches.flat()), + this.panelService.updatedDataBatches$.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(affected => { if (this.reportTemplate && affected.some(entityId => entityId.entityType === EntityType.REPORT_TEMPLATE && entityId.id === this.reportTemplate.id.id)) { - this.reportTemplateService.getReportTemplate(this.reportTemplate.id.id).subscribe(reportTemplate => this.init(reportTemplate)); + const reload = this.isDirty ? this.dialogService.confirm( + this.translate.instant('report-template.ai-reload-title'), + this.translate.instant('report-template.ai-reload-text'), + this.translate.instant('report-template.ai-reload-keep'), + this.translate.instant('report-template.ai-reload-confirm')) : of(true); + reload.pipe( + filter(Boolean), + switchMap(() => this.reportTemplateService.getReportTemplate(this.reportTemplate.id.id)) + ).subscribe(reportTemplate => this.init(reportTemplate)); } }); } diff --git a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template.module.ts b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template.module.ts index 612a8e9980..bb2535835c 100644 --- a/ui-ngx/src/app/modules/home/pages/reporting/template/report-template.module.ts +++ b/ui-ngx/src/app/modules/home/pages/reporting/template/report-template.module.ts @@ -30,7 +30,7 @@ import { } from '@home/pages/reporting/template/report-template-header-footer.component'; import { NotificationBellModule } from '@home/components/notification/notification-bell.module'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; @NgModule({ declarations: [ ReportTemplateFilterComponent, @@ -47,7 +47,7 @@ import { AiModule } from '@home/components/ai/ai.module'; CommonModule, SharedModule, HomeComponentsModule, - AiModule, + AiCoreModule, NotificationBellModule, HomeDialogsModule, ReportTemplateComponentsModule, diff --git a/ui-ngx/src/app/modules/home/pages/reporting/template/report-templates-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/reporting/template/report-templates-table-config.resolver.ts index d7c5dc960c..bf072da399 100644 --- a/ui-ngx/src/app/modules/home/pages/reporting/template/report-templates-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/reporting/template/report-templates-table-config.resolver.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { @@ -36,7 +37,7 @@ import { mergeMap } from 'rxjs/operators'; import { UtilsService } from '@core/services/utils.service'; import { AuthUser } from '@shared/models/user.model'; import { Authority } from '@shared/models/authority.enum'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ReportTemplateTableHeaderComponent } from '@home/pages/reporting/template/report-template-table-header.component'; @@ -63,6 +64,8 @@ import { @Injectable() export class ReportTemplatesTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private store: Store, private reportTemplateService: ReportTemplateService, private reportService: ReportService, @@ -241,19 +244,12 @@ export class ReportTemplatesTableConfigResolver { onAction: ($event) => this.importReportTemplate($event, config) } ); - if (this.aiAvailable()) { - actions.push({ - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.configureWithAi($event, config) - }); - } + actions.push(...this.aiAssistantConfigService.configureAction($event => this.configureWithAi($event, config))); return actions; } private aiAvailable(): boolean { - return getCurrentAuthState(this.store).aiEnabled && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } configureWithAi($event: Event, config: EntityTableConfig) { @@ -373,5 +369,4 @@ export class ReportTemplatesTableConfigResolver { return false; } - } diff --git a/ui-ngx/src/app/modules/home/pages/scada-symbol/scada-symbol.component.ts b/ui-ngx/src/app/modules/home/pages/scada-symbol/scada-symbol.component.ts index 3fcb2990cb..349b7d7ab2 100644 --- a/ui-ngx/src/app/modules/home/pages/scada-symbol/scada-symbol.component.ts +++ b/ui-ngx/src/app/modules/home/pages/scada-symbol/scada-symbol.component.ts @@ -15,7 +15,7 @@ import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActivatedRoute, Router } from '@angular/router'; -import { buffer, debounceTime, map, switchMap, takeUntil } from 'rxjs/operators'; +import { map, switchMap, takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; import { ScadaSymbolData, ScadaSymbolEditObjectCallbacks } from '@home/pages/scada-symbol/scada-symbol-editor.models'; import { @@ -42,14 +42,14 @@ import { UtilsService } from '@core/services/utils.service'; import { TranslateService } from '@ngx-translate/core'; import { Widget, WidgetConfig, widgetType, WidgetTypeDetails } from '@shared/models/widget.models'; import { - scadaSymbolWidgetDefaultSettings, - ScadaSymbolWidgetSettings + ScadaSymbolWidgetSettings, + scadaSymbolWidgetDefaultSettings } from '@home/components/widget/lib/scada/scada-symbol-widget.models'; import { WidgetActionCallbacks } from '@home/components/widget/action/manage-widget-actions.component.models'; import { ScadaSymbolMetadataComponent } from '@home/pages/scada-symbol/metadata-components/scada-symbol-metadata.component'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { EntityType } from '@shared/models/entity-type.models'; import { Authority } from '@shared/models/authority.enum'; @@ -72,8 +72,6 @@ import { Operation, Resource } from '@shared/models/security.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { ActionNotificationShow } from '@core/notification/notification.actions'; -const AI_RELOAD_DEBOUNCE_MS = 1000; - @Component({ selector: 'tb-scada-symbol', templateUrl: './scada-symbol.component.html', @@ -210,8 +208,7 @@ export class ScadaSymbolComponent extends PageComponent } private get aiAssistantAvailable(): boolean { - return getCurrentAuthState(this.store).aiEnabled && this.authUser.authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } private aiEditorDraftProvider = () => this.aiEditorDraft(); @@ -221,9 +218,7 @@ export class ScadaSymbolComponent extends PageComponent return; } this.panelService.setEditorDraftProvider(this.aiEditorDraftProvider); - this.panelService.updatedData$.pipe( - buffer(this.panelService.updatedData$.pipe(debounceTime(AI_RELOAD_DEBOUNCE_MS))), - map(batches => batches.flat()), + this.panelService.updatedDataBatches$.pipe( takeUntil(this.destroy$) ).subscribe(affected => { const id = this.symbolData?.imageResource?.id?.id; diff --git a/ui-ngx/src/app/modules/home/pages/security/security.component.ts b/ui-ngx/src/app/modules/home/pages/security/security.component.ts index 0253bc0f18..881a49b7eb 100644 --- a/ui-ngx/src/app/modules/home/pages/security/security.component.ts +++ b/ui-ngx/src/app/modules/home/pages/security/security.component.ts @@ -34,7 +34,7 @@ import { TwoFactorAuthProviderType } from '@shared/models/two-factor-auth.models'; import { authenticationDialogMap } from '@home/pages/security/authentication-dialog/authentication-dialog.map'; -import { filter, takeUntil, tap } from 'rxjs/operators'; +import { takeUntil, tap } from 'rxjs/operators'; import { Observable, of, Subject } from 'rxjs'; import { isDefinedAndNotNull } from '@core/utils'; import { Operation, Resource } from '@shared/models/security.models'; @@ -98,8 +98,7 @@ export class SecurityComponent extends PageComponent implements OnInit, OnDestro this.buildTwoFactorForm(); this.user = this.route.snapshot.data.user; this.twoFactorLoad(this.route.snapshot.data.providers); - this.aiAssistantPanelService.customizationSaved$.pipe( - filter(event => event.kind === 'ACCOUNT_SECURITY'), + this.aiAssistantPanelService.customizationReload$('ACCOUNT_SECURITY').pipe( takeUntil(this.destroy$) ).subscribe(() => { if (this.allowTwoFactorProviders.length) { @@ -193,7 +192,6 @@ export class SecurityComponent extends PageComponent implements OnInit, OnDestro const currentPassControl = group.get('currentPassword'); const newPassControl = group.get('newPassword'); - const current = currentPassControl?.value ?? ''; const newPass = newPassControl?.value ?? ''; diff --git a/ui-ngx/src/app/modules/home/pages/widget/widget-editor.component.ts b/ui-ngx/src/app/modules/home/pages/widget/widget-editor.component.ts index baf4c8c155..60cc4c4764 100644 --- a/ui-ngx/src/app/modules/home/pages/widget/widget-editor.component.ts +++ b/ui-ngx/src/app/modules/home/pages/widget/widget-editor.component.ts @@ -31,7 +31,7 @@ import { ActivatedRoute, Router } from '@angular/router'; import { deepClone } from '@core/utils'; import { HasDirtyFlag } from '@core/guards/confirm-on-exit.guard'; import { AuthUser } from '@shared/models/user.model'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { Authority } from '@shared/models/authority.enum'; import { NULL_UUID } from '@shared/models/id/has-uuid'; import { Hotkey } from 'angular2-hotkeys'; @@ -52,7 +52,7 @@ import { import { forkJoin, mergeMap, of, Subscription, throwError } from 'rxjs'; import { widgetEditorCompleter } from '@home/pages/widget/widget-editor.models'; import { Observable } from 'rxjs/internal/Observable'; -import { buffer, catchError, debounceTime, map, tap } from 'rxjs/operators'; +import { catchError, map, tap } from 'rxjs/operators'; import { beautifyCss, beautifyHtml, beautifyJs } from '@shared/models/beautify.models'; import { HttpClient, HttpStatusCode } from '@angular/common/http'; import { loadModulesCompleter } from '@shared/models/js-function.models'; @@ -67,12 +67,9 @@ import Timeout = NodeJS.Timeout; import { WhiteLabelingService } from '@core/http/white-labeling.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { EntityType } from '@shared/models/entity-type.models'; import { AiAssistantViewType } from '@shared/models/ai-chat.models'; -const AI_RELOAD_DEBOUNCE_MS = 1000; - // @dynamic @Component({ selector: 'tb-widget-editor', @@ -243,8 +240,7 @@ export class WidgetEditorComponent extends PageComponent implements OnInit, Afte } get aiAssistantAvailable(): boolean { - return getCurrentAuthState(this.store).aiEnabled && this.authUser.authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } private setupAiAssistant() { @@ -259,10 +255,7 @@ export class WidgetEditorComponent extends PageComponent implements OnInit, Afte this.isDirty = false; } })); - this.rxSubscriptions.push(this.panelService.updatedData$.pipe( - buffer(this.panelService.updatedData$.pipe(debounceTime(AI_RELOAD_DEBOUNCE_MS))), - map(batches => batches.flat()) - ).subscribe(affected => { + this.rxSubscriptions.push(this.panelService.updatedDataBatches$.subscribe(affected => { const id = this.widgetTypeDetails?.id?.id; if (id && affected.some(entityId => entityId.entityType === EntityType.WIDGET_TYPE && entityId.id === id)) { this.reloadFromServer(id); @@ -430,7 +423,6 @@ export class WidgetEditorComponent extends PageComponent implements OnInit, Afte const editorsObservables: Observable[] = []; - editorsObservables.push(this.createAceEditor(this.htmlInputElmRef, 'html').pipe( tap((editor) => { this.htmlEditor = editor; diff --git a/ui-ngx/src/app/modules/home/pages/widget/widget-library.module.ts b/ui-ngx/src/app/modules/home/pages/widget/widget-library.module.ts index 07ebea9e50..a914772179 100644 --- a/ui-ngx/src/app/modules/home/pages/widget/widget-library.module.ts +++ b/ui-ngx/src/app/modules/home/pages/widget/widget-library.module.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@shared/shared.module'; @@ -19,7 +20,7 @@ import { WidgetConfigComponentsModule } from '@home/components/widget/config/wid import { GithubBadgeModule } from '@home/components/github-badge/github-badge.module'; import { NotificationBellModule } from '@home/components/notification/notification-bell.module'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; @NgModule({ declarations: [ WidgetTypeComponent, @@ -37,7 +38,7 @@ import { AiModule } from '@home/components/ai/ai.module'; CommonModule, SharedModule, HomeComponentsModule, - AiModule, + AiCoreModule, GithubBadgeModule, NotificationBellModule, WidgetConfigComponentsModule, diff --git a/ui-ngx/src/app/modules/home/pages/widget/widget-types-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/widget/widget-types-table-config.resolver.ts index 56a4ffdbf7..6a87600d17 100644 --- a/ui-ngx/src/app/modules/home/pages/widget/widget-types-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/widget/widget-types-table-config.resolver.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { Router } from '@angular/router'; import { @@ -46,6 +47,8 @@ export class WidgetTypesTableConfigResolver { private readonly config: EntityTableConfig = new EntityTableConfig(); + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private store: Store, private dialog: MatDialog, private widgetsService: WidgetService, @@ -112,7 +115,6 @@ export class WidgetTypesTableConfigResolver { this.config.deleteEntitiesTitle = count => this.translate.instant('widget.delete-widgets-title', {count}); this.config.deleteEntitiesContent = () => this.translate.instant('widget.delete-widgets-text'); - this.config.loadEntity = id => this.widgetsService.getWidgetTypeById(id.id); this.config.saveEntity = widgetType => this.widgetsService.saveWidgetType(widgetType as WidgetTypeDetails); this.config.deleteEntity = id => this.widgetsService.deleteWidgetType(id.id); @@ -150,12 +152,7 @@ export class WidgetTypesTableConfigResolver { view: {listView: AiAssistantViewType.WIDGET_TYPE_LIST, entityView: AiAssistantViewType.WIDGET_TYPE}, initialPromptPlaceholder: this.translate.instant('widget.ai-assistant-initial-prompt-placeholder') }; - this.config.addActionDescriptors.push({ - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => true, - onAction: ($event) => this.configureWithAi($event) - }); + this.config.addActionDescriptors.push(...this.aiAssistantConfigService.configureAction($event => this.configureWithAi($event))); } else { this.config.aiAssistantConfig = null; } @@ -207,8 +204,7 @@ export class WidgetTypesTableConfigResolver { private aiAvailable(): boolean { const authState = getCurrentAuthState(this.store); - return authState.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } configureWithAi($event: Event): void { diff --git a/ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.ts b/ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.ts index 6afe7e04b2..59e0d7dcc2 100644 --- a/ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.ts +++ b/ui-ngx/src/app/modules/home/pages/widget/widgets-bundle-widgets.component.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { ChangeDetectorRef, Component, DestroyRef, inject, OnDestroy, OnInit } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { AuthUser } from '@shared/models/user.model'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActivatedRoute, Router } from '@angular/router'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { Authority } from '@shared/models/authority.enum'; import { NULL_UUID } from '@shared/models/id/has-uuid'; import { WidgetsBundle } from '@shared/models/widgets-bundle.model'; @@ -20,13 +21,9 @@ import { SelectWidgetTypeDialogComponent } from '@home/pages/widget/select-widge import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; import { EntityType } from '@shared/models/entity-type.models'; import { AiAssistantViewType } from '@shared/models/ai-chat.models'; import { TranslateService } from '@ngx-translate/core'; -import { buffer, debounceTime, map } from 'rxjs/operators'; - -const AI_RELOAD_DEBOUNCE_MS = 1000; type WidgetTypeBundle = WithOptional; @@ -95,8 +92,7 @@ export class WidgetsBundleWidgetsComponent extends PageComponent implements OnIn } get aiAssistantAvailable(): boolean { - return getCurrentAuthState(this.store).aiEnabled && this.authUser.authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL); + return this.userPermissionsService.isAiAvailable(); } private setupAiAssistant() { @@ -113,9 +109,7 @@ export class WidgetsBundleWidgetsComponent extends PageComponent implements OnIn entityId: {entityType: EntityType.WIDGETS_BUNDLE, id: this.widgetsBundle.id.id} }); this.panelService.setViewName(this.widgetsBundle.title); - this.panelService.updatedData$.pipe( - buffer(this.panelService.updatedData$.pipe(debounceTime(AI_RELOAD_DEBOUNCE_MS))), - map(batches => batches.flat()), + this.panelService.updatedDataBatches$.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(affected => { const id = this.widgetsBundle.id.id; diff --git a/ui-ngx/src/app/modules/home/pages/widget/widgets-bundles-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/widget/widgets-bundles-table-config.resolver.ts index 9297cb997c..4297373014 100644 --- a/ui-ngx/src/app/modules/home/pages/widget/widgets-bundles-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/widget/widgets-bundles-table-config.resolver.ts @@ -118,8 +118,7 @@ export class WidgetsBundlesTableConfigResolver { this.config.tableTitle = this.translate.instant('widgets-bundle.widgets-bundles'); const authUser = getCurrentAuthUser(this.store); const authState = getCurrentAuthState(this.store); - this.config.aiAssistantConfig = authState.aiEnabled && authUser.authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) ? { + this.config.aiAssistantConfig = this.userPermissionsService.isAiAvailable() ? { view: {listView: AiAssistantViewType.WIDGETS_BUNDLE_LIST, entityView: AiAssistantViewType.WIDGETS_BUNDLE}, initialPromptPlaceholder: this.translate.instant('widget.ai-assistant-initial-prompt-placeholder') } : null; diff --git a/ui-ngx/src/app/modules/tour/tour-launcher.service.ts b/ui-ngx/src/app/modules/tour/tour-launcher.service.ts index 76c9575441..9ada5a1e03 100644 --- a/ui-ngx/src/app/modules/tour/tour-launcher.service.ts +++ b/ui-ngx/src/app/modules/tour/tour-launcher.service.ts @@ -173,7 +173,11 @@ export class TourLauncher implements TourLauncherApi { const stop = stops[index]; await stop.enter?.(); const target = stop.target(); - if (over || !target) { + if (over) { + return; + } + if (!target) { + await go(index + 1); return; } const live = stops.filter(s => !!s.target()); diff --git a/ui-ngx/src/app/modules/tour/welcome-invitation.component.html b/ui-ngx/src/app/modules/tour/welcome-invitation.component.html index 8e6353e546..9e00f9889a 100644 --- a/ui-ngx/src/app/modules/tour/welcome-invitation.component.html +++ b/ui-ngx/src/app/modules/tour/welcome-invitation.component.html @@ -18,7 +18,7 @@

    {{ 'tour.invite.card-' + k + '.title' | translate }}

    {{ 'tour.invite.card-' + k + '.lead' | translate }}

    } @else { -

    {{ ('tour.invite.pill-' + person | translate) + ': ' + ('tour.invite.news' | translate) + ' ' + ('tour.invite.cover-title' | translate) }}

    +

    {{ ('tour.invite.pill-' + person | translate) + ': ' + ('tour.invite.news' | translate) + ' ' + ('tour.invite.cover-title' | translate) }}

    {{ 'tour.invite.cover-lead' | translate }}

    }
    diff --git a/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss b/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss index 969332cbb0..c4a86e92b0 100644 --- a/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss +++ b/ui-ngx/src/app/modules/tour/welcome-invitation.component.scss @@ -40,15 +40,6 @@ --tb-widget-shadow: 0 1px 1px rgba(20, 52, 58, 0.06), 0 2px 6px -1px rgba(20, 52, 58, 0.08); --tb-widget-radius: 12px; - .tb-sr-only { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; - } - .iv-x.mat-mdc-icon-button.mat-mdc-button-base { --mdc-icon-button-state-layer-size: 36px; --mat-icon-button-state-layer-size: 36px; @@ -60,9 +51,7 @@ .iv-go { --mat-button-filled-container-color: var(--ai-action); - --mdc-filled-button-container-color: var(--ai-action); --mat-button-filled-label-text-color: var(--ai-on-action); - --mdc-filled-button-label-text-color: var(--ai-on-action); } .ai-field { @@ -195,10 +184,6 @@ .rq-term-foot { display: flex; align-items: center; gap: 2px; padding: 2px 8px 6px; border-top: 1px solid var(--tb-line-soft); font: 400 12px/16px var(--tb-font); color: var(--tb-text-secondary); } .rq-tool { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; } .rq-tool .mat-icon { font-size: 18px; width: 18px; height: 18px; color: var(--tb-ink-54); } -.rq-cring svg { display: block; width: 20px; height: 20px; } -.rq-cring circle { fill: none; stroke-width: 2.5; } -.rq-cring .track { stroke: rgba(0, 0, 0, 0.1); } -.rq-cring .arc { stroke: var(--ai-teal-500); stroke-linecap: round; } .rq-term.compact .rq-term-in { min-height: 0; padding: 10px 8px 10px 12px; } .rq-term.compact .rq-send { align-self: center; width: 32px; height: 32px; } .rq-term.compact .rq-pre { height: 22px; line-height: 22px; } diff --git a/ui-ngx/src/app/shared/components/markdown.component.ts b/ui-ngx/src/app/shared/components/markdown.component.ts index 70eb3dc78a..ddeacb71a2 100644 --- a/ui-ngx/src/app/shared/components/markdown.component.ts +++ b/ui-ngx/src/app/shared/components/markdown.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { ChangeDetectorRef, Component, @@ -67,6 +68,10 @@ export class TbMarkdownComponent implements OnChanges { @coerceBoolean() usePlainMarkdown = false; + @Input() + @coerceBoolean() + highlight = true; + @Output() ready = new EventEmitter(); isMarkdownReady = false; @@ -113,7 +118,9 @@ export class TbMarkdownComponent implements OnChanges { const element: HTMLDivElement = this.renderer.createElement('div'); element.innerHTML = template; this.handlePlugins(element); - this.markdownService.highlight(element); + if (this.highlight) { + this.markdownService.highlight(element); + } const preElements = element.querySelectorAll('pre'); const matches = Array.from(template.matchAll(/)<\/pre>/g)); for (let i = 0; i < preElements.length; i++) { diff --git a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html index a006ba1ea8..1916551872 100644 --- a/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html +++ b/ui-ngx/src/app/shared/components/password-requirements-tooltip.component.html @@ -1,7 +1,8 @@ { return items; }; +const LEGACY_MENU_IDS: Record = { + ai_solution_creator: 'ai_assistant' +}; + +export const withCurrentMenuIds = (config: CustomMenuConfig): CustomMenuConfig => { + if (!config?.items) { + return config; + } + const legacy = (items: MenuItem[]): boolean => items.some(item => !!LEGACY_MENU_IDS[item.id] || (!!item.pages && legacy(item.pages))); + if (!legacy(config.items)) { + return config; + } + const seen = new Set(); + const migrate = (items: MenuItem[]): MenuItem[] => items.flatMap(item => { + const id = LEGACY_MENU_IDS[item.id] ?? item.id; + if (id && seen.has(id)) { + return []; + } + if (id) { + seen.add(id); + } + return [{...item, ...(id ? {id: id as MenuId} : {}), ...(item.pages ? {pages: migrate(item.pages)} : {})}]; + }); + return {...config, items: migrate(config.items)}; +}; + const mergeFromDefaultMenu = (items: MenuItem[], defaultItems: MenuItem[]): MenuItem[] => { const menuItems: MenuItem[] = []; const defaultItemsMap = new Map(defaultItems.map(item => [item.id, item])); @@ -301,6 +327,7 @@ export const afterLoadCustomMenuConfig = (config: CustomMenuConfig, scope: CMSco if (!config?.items?.length) { return defaultMenuConfig; } else { + config = withCurrentMenuIds(config); config.items = afterLoadMenuItems(mergeFromDefaultMenu(config.items, defaultMenuConfig.items)); return config; } diff --git a/ui-ngx/src/app/shared/models/device.models.ts b/ui-ngx/src/app/shared/models/device.models.ts index b63d77e2fb..21561dcdd3 100644 --- a/ui-ngx/src/app/shared/models/device.models.ts +++ b/ui-ngx/src/app/shared/models/device.models.ts @@ -29,8 +29,6 @@ import type { Store } from '@ngrx/store'; import type { AppState } from '@core/core.state'; import type { TranslateService } from '@ngx-translate/core'; import type { UserPermissionsService } from '@core/http/user-permissions.service'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; -import { Operation, Resource } from '@shared/models/security.models'; import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; export enum DeviceProfileType { @@ -110,7 +108,6 @@ export const deviceTransportTypeTranslationMap = new Map( ] ); - export const deviceProvisionTypeTranslationMap = new Map( [ [DeviceProvisionType.DISABLED, 'device-profile.provision-strategy-disabled'], @@ -191,7 +188,6 @@ export const coapDeviceTypeTranslationMap = new Map( [ [ @@ -571,7 +567,6 @@ export const deviceProfileAlarmValidator = (control: AbstractControl): Validatio return {deviceProfileAlarm: true}; }; - export interface DeviceProfileData { configuration: DeviceProfileConfiguration; transportConfiguration: DeviceProfileTransportConfiguration; @@ -905,9 +900,7 @@ export function deviceAiAssistantConfig(store: Store, entityView?: AiAssistantViewType, listView: AiAssistantViewType = AiAssistantViewType.DEVICE_LIST, listEntityId?: EntityId): AiAssistantPanelConfig | null { - const hasPermission = getCurrentAuthState(store).aiEnabled && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - hasDevicePermission; + const hasPermission = userPermissionsService.isAiAvailable() && hasDevicePermission; if (!hasPermission) { return null; } diff --git a/ui-ngx/src/app/shared/models/notification.models.ts b/ui-ngx/src/app/shared/models/notification.models.ts index d2a2b5c4f3..49ac213139 100644 --- a/ui-ngx/src/app/shared/models/notification.models.ts +++ b/ui-ngx/src/app/shared/models/notification.models.ts @@ -20,7 +20,6 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { TranslateService } from '@ngx-translate/core'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { Operation, Resource } from '@shared/models/security.models'; import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; import { Authority } from '@shared/models/authority.enum'; @@ -866,8 +865,7 @@ export function notificationAiAssistantConfig(store: Store, userPermissionsService: UserPermissionsService, translate: TranslateService, listView: AiAssistantViewType): AiAssistantPanelConfig | null { - const hasPermission = getCurrentAuthState(store).aiEnabled && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && + const hasPermission = userPermissionsService.isAiAvailable() && userPermissionsService.hasGenericPermission(Resource.NOTIFICATION, Operation.WRITE); if (!hasPermission) { return null; diff --git a/ui-ngx/src/app/shared/models/password.models.ts b/ui-ngx/src/app/shared/models/password.models.ts index d04b4da5a6..11c501deba 100644 --- a/ui-ngx/src/app/shared/models/password.models.ts +++ b/ui-ngx/src/app/shared/models/password.models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { UserPasswordPolicy } from '@shared/models/settings.models'; import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { isEqual } from '@core/utils'; diff --git a/ui-ngx/src/app/shared/models/settings.models.ts b/ui-ngx/src/app/shared/models/settings.models.ts index e4218859b4..b56b0a285e 100644 --- a/ui-ngx/src/app/shared/models/settings.models.ts +++ b/ui-ngx/src/app/shared/models/settings.models.ts @@ -549,10 +549,3 @@ export interface LicenseInfo { plan: string; } -export interface LicenseUsageInfo extends LicenseInfo { - devicesCount: number; - assetsCount: number; - edgesCount: number; - dashboardsCount: number; - integrationsCount: number; -} diff --git a/ui-ngx/src/app/shared/models/user-settings.models.ts b/ui-ngx/src/app/shared/models/user-settings.models.ts index ae2a55e322..e9a4b9c1ef 100644 --- a/ui-ngx/src/app/shared/models/user-settings.models.ts +++ b/ui-ngx/src/app/shared/models/user-settings.models.ts @@ -11,7 +11,6 @@ export interface UserSettings { includeBundleWidgetsInExport?: boolean; includeResourcesInExportWidgetTypes?: boolean; includeResourcesInExportDashboard?: boolean; - isSolutionSidebarExpanded?: boolean; aiTour?: AiTourSettings; homeCards?: HomeCardsSettings; } diff --git a/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md b/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md index 462d386cae..b08b5cbb3f 100644 --- a/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md +++ b/ui-ngx/src/assets/help/en_US/notification/ai_credits_limit_increase_request.md @@ -14,7 +14,11 @@ Available template parameters: * `limitDescription` - which AI credits are used up, ex. 'its monthly limit of 5,000,000 AI credits' or 'all AI credits of this installation's license'; * `increaseLimitActionLabel` - label of the button, 'Set new limit' or 'Add credits'; * `increaseLimitLink` - link to the tenant page, or to the License Management page when the installation's AI credits are used up; -* `baseUrl` - used to construct the full URL of the link in email notifications; +* `baseUrl` - used to construct the full URL of the link in email notifications; +* `recipientTitle` - title of the recipient (first and last name if specified, email otherwise); +* `recipientEmail` - email of the recipient; +* `recipientFirstName` - first name of the recipient; +* `recipientLastName` - last name of the recipient; Parameter names must be wrapped using `${...}`. For example: `${userEmail}`. You may also modify the value of the parameter with one of the suffixes: diff --git a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json index b94fe3dbdc..9c291e931d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "التهيئة باستخدام الذكاء الاصطناعي", - "follow-up-prompt-placeholder": "ردّ...", - "sub-title": "يمكنني مساعدتك في إعداد وإدارة الأجهزة ولوحات المعلومات والحقول المحسوبة وقواعد الإنذار والإشعارات الخاصة بك — فقط صِف ما تحتاج إليه وسأتولى الباقي.", "new-chat": "محادثة جديدة", - "no-chats": "لا توجد محادثات بعد", "today": "اليوم", "yesterday": "الأمس", "last-7-days": "آخر 7 أيام", @@ -703,17 +700,11 @@ "delete-chat-title": "هل أنت متأكد أنك تريد حذف '{{name}}'؟", "delete-chat-text": "ستُفقد جميع رسائل المحادثة", "delete-chat-confirm": "نعم، احذف", - "action-approval-required": "الموافقة على الإجراء مطلوبة", "approve": "موافقة", - "approve-all": "الموافقة على جميع الإجراءات اللاحقة", "deny": "رفض", - "processing": "جارٍ المعالجة...", "approved": "تم", - "denied": "مرفوض", "error": "فشل", "thinking": "جارٍ التفكير...", - "connection-lost": "انقطع الاتصال بمساعد الذكاء الاصطناعي. جارٍ إعادة الاتصال...", - "reconnect-failed": "تعذّرت إعادة الاتصال بمساعد الذكاء الاصطناعي. أعد فتح المحادثة لرؤية ردّه.", "ask-the-assistant": "اسأل مساعد الذكاء الاصطناعي", "send": "إرسال", "new-line": "سطر جديد", @@ -740,9 +731,7 @@ "text": "نص", "file": "ملف" }, - "rename-chat-title": "إعادة تسمية هذه المحادثة", - "export-chat": "تصدير المحادثة", - "main-title": "مرحبًا! أنا مساعد الذكاء الاصطناعي الخاص بك" + "export-chat": "تصدير المحادثة" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "اقتراح قواعد إنذار", @@ -11319,47 +11308,20 @@ "select-recaptcha-enterprise-service-account-file": "اسحب ملف بيانات اعتماد حسابك وأفلته" }, "solution-creator": { - "ai-solution-creator": "مُنشئ الحلول بالذكاء الاصطناعي", "describe-solution-you-want": "صف الحل الذي تريد إنشاءه", - "enter-your-prompt": "أدخل مطالبتك", "target": "الهدف", "install-solution": "تثبيت", - "solution-overview": "نظرة عامة على الحل: {{ name }}", - "dashboards-overview": "نظرة عامة على لوحات المعلومات: {{ name }}", - "entity-profile": "ملف تعريف الكيان", - "entity-profiles": "ملفات تعريف الكيانات", - "name": "الاسم", - "iam": "IAM", - "iam-full": "إدارة الهوية والوصول", - "table-view": "جدول", - "schema-view": "مخطط", - "iam-info": "معلومات IAM", "operation": { "C": "إنشاء", "R": "قراءة", "U": "تحديث", "D": "حذف" }, - "alarm-info": "معلومات الإنذار", "description": "الوصف", - "data": "البيانات", - "entity-info": "معلومات الكيان", - "calculated-field-info": "معلومات الحقل المحسوب", - "field-type": "نوع الحقل", - "scope": "النطاق", "delete-alarm-title": "هل تريد حذف هذا الإنذار المقترح؟", "delete-alarm-text": "لن تتم إضافة هذا الإنذار، المقترح بناءً على وصفك، إلى بنية الحل المقترح.
    يمكنك دائمًا تعديل الإنذارات أو إعادة إنشائها يدويًا لاحقًا. لا يمكن التراجع عن هذا الإجراء.", - "basic-mode": "أساسي", - "advanced-mode": "متقدم", "create-solution": "إنشاء الحل", "go-dashboard-manager": "التالي: تصميم لوحة المعلومات", - "success-generate-title": "الحل جاهز!", - "success-generate-sub-title": "يمكنك تثبيته على حسابك بالنقر على الزر أدناه", - "success-generate-install-title": "تم تثبيت الحل!", - "success-generate-install-sub-title": "لتعديل الحل، يرجى إلغاء تثبيت المثيل الحالي أولًا", - "main-title": "مرحبًا! أنا مساعد الذكاء الاصطناعي الخاص بك", - "sub-title": "أساعدك على تحويل متطلباتك إلى حل IoT متكامل وجاهز للعمل.\nما عليك سوى وصف ما تريد تحقيقه، وسأتولى الباقي.", - "solutions": "الحلول", "new-solution": "حل جديد", "uninstall-solution": "إلغاء التثبيت", "uninstall-solution-dialog-title": "هل أنت متأكد أنك تريد إلغاء تثبيت \"{{ name }}\"؟", @@ -11369,12 +11331,8 @@ "delete-solution-text": "ستفقد جميع بياناتك", "delete-solution-confirm": "نعم، حذف", "copy-solution": "نسخ الحل", - "expand-sidebar": "توسيع الشريط الجانبي", - "collapse-sidebar": "طي الشريط الجانبي", "solution-id": "معرّف الحل", "solution-id-required": "معرّف الحل مطلوب", - "rename-solution-title": "إعادة تسمية هذا الحل", - "generate-again": "إعادة التوليد", "skip-interview": "تخطي المقابلة", "update-solution": "تحديث الحل", "finish-edit": "إنهاء التعديل", @@ -11384,8 +11342,6 @@ "water-metering": "قياس استهلاك المياه", "coffee-machine-monitoring": "مراقبة آلات القهوة", "fleet-geofencing": "السياج الجغرافي للأسطول", - "more-examples": "المزيد من الأمثلة", - "hide": "إخفاء", "solution-info": "معلومات الحل", "solution-info-with-name": "معلومات الحل: {{ name }}", "status": "الحالة", @@ -11398,14 +11354,8 @@ "info": "معلومات", "main-dashboard": "لوحة المعلومات الرئيسية", "view-as": "عرض بصفة {{ name }}", - "generated-by-calculated-field-name": "تم إنشاؤه بواسطة الحقل المحسوب \"{{ name }}\"", "estimate-wait-time": "وقت الانتظار المقدّر ~{{ time }}", - "analyzing-your-request": "جارٍ تحليل طلبك...", "condition": "الشرط", - "installing": "جارٍ تثبيت الحل...", - "step-architecture-design": "تصميم البنية", - "step-dashboard-design": "تصميم لوحة المعلومات", - "step-solution-installation": "تثبيت الحل", "step-reading-device-data": "جارٍ قراءة بيانات الجهاز…", "step-analyzing-telemetry-attributes": "جارٍ تحليل القياس عن بُعد والسمات…", "step-selecting-widgets": "جارٍ اختيار الأدوات المناسبة لبياناتك…", @@ -11437,11 +11387,7 @@ "step-loading-building-alarm-rules": "جارٍ بناء قواعد الإنذار…", "step-loading-assembling-dashboards": "جارٍ تجميع لوحات المعلومات…", "step-loading-preparing-states": "جارٍ تحضير الحالات…", - "step-loading-initializing-solution": "جارٍ تهيئة الحل…", - "ai-credits": "أرصدة الذكاء الاصطناعي", - "ai-credits-update": "تغيير الخطة", - "ai-credits-usage": "أرصدة الذكاء الاصطناعي: تم استخدام {{ used }} من {{ max }}", - "ai-credits-description": "لقد استخدمت {{ used }} من أصل {{ max }} من أرصدة الذكاء الاصطناعي هذا الشهر. تتم إعادة تعيين الحد في {{ date }}. لزيادة حصتك من أرصدة الذكاء الاصطناعي، يرجى التواصل مع مسؤول النظام." + "step-loading-initializing-solution": "جارٍ تهيئة الحل…" }, "markdown": { "edit": "تعديل", @@ -13874,11 +13820,6 @@ "disk-warning-text": "انخفاض مساحة القرص المتاحة. لتجنب فقدان البيانات، حرِّر مساحة على القرص أو وسِّع مساحته.", "disk-critical-text": "انخفاض حرج في مساحة القرص المتاحة. لتجنب فقدان البيانات، حرِّر مساحة على القرص أو وسِّع مساحته." }, - "cluster-info": { - "service-id": "معرف الخدمة", - "service-type": "نوع الخدمة", - "no-data": "لا تتوفر بيانات" - }, "transport-messages": { "title": "رسائل النقل", "info": "كل الرسائل التي تأتي من الأجهزة" @@ -13917,41 +13858,9 @@ "no-last-viewed-dashboards": "لا توجد لوحات معلومات تمت مشاهدتها مؤخرًا بعد" }, "configured-features": { - "title": "الميزات المُكوَّنة", - "info": "حالة الميزات التي تتطلب تكوينًا", - "white-labeling-feature": "تخصيص العلامة التجارية", - "email-feature": "البريد الإلكتروني", - "sms-feature": "رسائل SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "المصادقة بخطوتين", "feature-configured": "الميزة مكونة.\nانقر لإعدادها", "feature-not-configured": "الميزة غير مكونة.\nانقر لإعدادها" }, - "version-info": { - "title": "الإصدار", - "contact-us": "اتصل بنا", - "current-version": "الإصدار الحالي", - "current": "الحالي", - "available-version": "الإصدار المتاح", - "available": "متاح", - "upgrade": "الترقية", - "version-is-up-to-date": "الإصدار محدَّث" - }, - "license-info": { - "title": "معلومات الترخيص", - "view-all": "عرض الكل", - "license-portal": "بوابة الترخيص", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } أجهزة", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } أصول", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } مثيلات Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } لوحات معلومات", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } تكاملات", - "community-support": "دعم المجتمع", - "white-labeling": "تخصيص العلامة التجارية", - "unlimited-datapoints-and-messages": "نقاط البيانات والرسائل غير محدودة", - "unlimited-api-calls": "استدعاءات API غير محدودة" - }, "usage-info": { "title": "استخدام", "entities": "الكيانات", diff --git a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json index 6b21ea6f4d..a1b31ddd1e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configura amb IA", - "follow-up-prompt-placeholder": "Respon...", - "sub-title": "Puc ajudar-vos a configurar i gestionar els vostres dispositius, taulers, camps calculats, regles d'alarma i notificacions: només heu de descriure què necessiteu i jo m'encarrego de la resta.", "new-chat": "Nou xat", - "no-chats": "Encara no hi ha xats", "today": "Avui", "yesterday": "Ahir", "last-7-days": "Últims 7 dies", @@ -703,17 +700,11 @@ "delete-chat-title": "Esteu segur que voleu suprimir '{{name}}'?", "delete-chat-text": "Es perdran tots els missatges del xat", "delete-chat-confirm": "Sí, suprimeix", - "action-approval-required": "Cal aprovar l'acció", "approve": "Aprova", - "approve-all": "Aprova totes les accions posteriors", "deny": "Denega", - "processing": "S'està processant...", "approved": "Fet", - "denied": "Denegat", "error": "Ha fallat", "thinking": "Pensant...", - "connection-lost": "S'ha perdut la connexió amb l'assistent d'IA. S'està tornant a connectar...", - "reconnect-failed": "No s'ha pogut tornar a connectar amb l'assistent d'IA. Torneu a obrir el xat per veure'n la resposta.", "ask-the-assistant": "Pregunteu a l'assistent d'IA", "send": "Envia", "new-line": "Línia nova", @@ -740,9 +731,7 @@ "text": "Text", "file": "Fitxer" }, - "rename-chat-title": "Canvia el nom d'aquest xat", - "export-chat": "Exporta el xat", - "main-title": "Hola! Soc el vostre assistent d'IA" + "export-chat": "Exporta el xat" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Suggereix regles d'alarma", @@ -11324,47 +11313,20 @@ "select-recaptcha-enterprise-service-account-file": "Arrossegueu i deixeu anar el fitxer de credencials del compte" }, "solution-creator": { - "ai-solution-creator": "Creador de solucions amb IA", "describe-solution-you-want": "Descriviu la solució que voleu crear", - "enter-your-prompt": "Introduïu la vostra indicació", "target": "Destinació", "install-solution": "Instal·la", - "solution-overview": "Resum de la solució: {{ name }}", - "dashboards-overview": "Resum dels taulers: {{ name }}", - "entity-profile": "Perfil d'entitat", - "entity-profiles": "Perfils d'entitat", - "name": "Nom", - "iam": "IAM", - "iam-full": "Gestió d'identitats i accessos", - "table-view": "Taula", - "schema-view": "Esquema", - "iam-info": "Informació d'IAM", "operation": { "C": "Crea", "R": "Llegeix", "U": "Actualitza", "D": "Suprimeix" }, - "alarm-info": "Informació de l'alarma", "description": "Descripció", - "data": "Dades", - "entity-info": "Informació de l'entitat", - "calculated-field-info": "Informació del camp calculat", - "field-type": "Tipus de camp", - "scope": "Àmbit", "delete-alarm-title": "Voleu suprimir aquesta alarma suggerida?", "delete-alarm-text": "Aquesta alarma, suggerida a partir de la vostra descripció, no s'afegirà a la construcció de la solució proposada.
    Sempre podeu editar o tornar a crear les alarmes manualment més endavant. Aquesta acció no es pot desfer.", - "basic-mode": "Bàsic", - "advanced-mode": "Avançat", "create-solution": "Crea una solució", "go-dashboard-manager": "Següent: disseny del tauler", - "success-generate-title": "La solució està a punt!", - "success-generate-sub-title": "Podeu instal·lar-la al vostre compte fent clic al botó de sota", - "success-generate-install-title": "Solució instal·lada!", - "success-generate-install-sub-title": "Per editar la solució, primer desinstal·leu la instància existent", - "main-title": "Hola! Soc el vostre assistent d'IA", - "sub-title": "Us ajudo a transformar els vostres requisits en una solució IoT completament funcional.\nNomés cal que descriviu què voleu aconseguir, i jo m'encarrego de la resta.", - "solutions": "Solucions", "new-solution": "Solució nova", "uninstall-solution": "Desinstal·la", "uninstall-solution-dialog-title": "Esteu segur que voleu desinstal·lar ‘{{ name }}’?", @@ -11374,12 +11336,8 @@ "delete-solution-text": "Es perdran totes les vostres dades", "delete-solution-confirm": "Sí, suprimeix", "copy-solution": "Copia la solució", - "expand-sidebar": "Expandeix la barra lateral", - "collapse-sidebar": "Contrau la barra lateral", "solution-id": "ID de la solució", "solution-id-required": "L'ID de la solució és obligatori", - "rename-solution-title": "Canvia el nom d'aquesta solució", - "generate-again": "Torna a generar", "skip-interview": "Omet l'entrevista", "update-solution": "Actualitza la solució", "finish-edit": "Finalitza l'edició", @@ -11389,8 +11347,6 @@ "water-metering": "Mesurament del consum d'aigua", "coffee-machine-monitoring": "Monitoratge de màquines de cafè", "fleet-geofencing": "Geotancament de flotes", - "more-examples": "Més exemples", - "hide": "Amaga", "solution-info": "Informació de la solució", "solution-info-with-name": "Informació de la solució: {{ name }}", "status": "Estat", @@ -11403,14 +11359,8 @@ "info": "Informació", "main-dashboard": "Tauler principal", "view-as": "Visualitza com a {{ name }}", - "generated-by-calculated-field-name": "Generat pel camp calculat ‘{{ name }}’", "estimate-wait-time": "El temps d'espera estimat és de ~{{ time }}", - "analyzing-your-request": "S'està analitzant la vostra sol·licitud...", "condition": "Condició", - "installing": "S'està instal·lant la solució...", - "step-architecture-design": "Disseny de l'arquitectura", - "step-dashboard-design": "Disseny del tauler", - "step-solution-installation": "Instal·lació de la solució", "step-reading-device-data": "S'estan llegint les dades del dispositiu…", "step-analyzing-telemetry-attributes": "S'estan analitzant la telemetria i els atributs…", "step-selecting-widgets": "S'estan seleccionant ginys per a les vostres dades…", @@ -11442,11 +11392,7 @@ "step-loading-building-alarm-rules": "S'estan construint les regles d'alarma…", "step-loading-assembling-dashboards": "S'estan muntant els taulers…", "step-loading-preparing-states": "S'estan preparant els estats…", - "step-loading-initializing-solution": "S'està inicialitzant la solució…", - "ai-credits": "Crèdits d'IA", - "ai-credits-update": "Canvia el pla", - "ai-credits-usage": "Crèdits d'IA: {{ used }} de {{ max }} utilitzats", - "ai-credits-description": "Heu utilitzat {{ used }} dels vostres {{ max }} crèdits d'IA aquest mes. El límit es restableix el {{ date }}. Per augmentar la vostra quota de crèdits d'IA, contacteu amb l'administrador del sistema." + "step-loading-initializing-solution": "S'està inicialitzant la solució…" }, "markdown": { "edit": "Edita", @@ -13879,11 +13825,6 @@ "disk-warning-text": "Queda poc espai al disc. Per evitar la pèrdua de dades, allibereu o amplieu l'espai del disc.", "disk-critical-text": "Espai al disc críticament baix. Per evitar la pèrdua de dades, allibereu o amplieu l'espai del disc." }, - "cluster-info": { - "service-id": "ID del servei", - "service-type": "Tipus de servei", - "no-data": "No hi ha dades" - }, "transport-messages": { "title": "Missatges de transport", "info": "Tots els missatges que han arribat dels dispositius" @@ -13922,41 +13863,9 @@ "no-last-viewed-dashboards": "Encara no hi ha taulers vistos recentment" }, "configured-features": { - "title": "Funcionalitats configurades", - "info": "Estat de les funcionalitats que requereixen configuració", - "white-labeling-feature": "Marca blanca", - "email-feature": "Correu electrònic", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "La funcionalitat està configurada.\nFeu clic per configurar-la", "feature-not-configured": "La funcionalitat no està configurada.\nFeu clic per configurar-la" }, - "version-info": { - "title": "Versió", - "contact-us": "Contacteu-nos", - "current-version": "Versió actual", - "current": "Actual", - "available-version": "Versió disponible", - "available": "Disponible", - "upgrade": "Actualitza la versió", - "version-is-up-to-date": "La versió està actualitzada" - }, - "license-info": { - "title": "Informació de la llicència", - "view-all": "Mostra-ho tot", - "license-portal": "Portal de llicències", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } dispositius", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } actius", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } instàncies d'Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } taulers", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integracions", - "community-support": "Suport de la comunitat", - "white-labeling": "Marca blanca", - "unlimited-datapoints-and-messages": "Punts de dades i missatges il·limitats", - "unlimited-api-calls": "Crides a l'API il·limitades" - }, "usage-info": { "title": "Ús", "entities": "Entitats", diff --git a/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json b/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json index 801c079910..404ba066ee 100644 --- a/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json +++ b/ui-ngx/src/assets/locale/locale.constant-cs_CZ.json @@ -243,10 +243,7 @@ }, "ai-assistant": { "configure-with-ai": "Nakonfigurovat pomocí AI", - "follow-up-prompt-placeholder": "Odpovědět...", - "sub-title": "Mohu vám pomoci nastavit a spravovat vaše zařízení, dashboardy, vypočítaná pole, pravidla alarmů a oznámení — stačí popsat, co potřebujete, a o zbytek se postarám.", "new-chat": "Nový chat", - "no-chats": "Zatím žádné chaty", "today": "Dnes", "yesterday": "Včera", "last-7-days": "Posledních 7 dní", @@ -254,16 +251,11 @@ "delete-chat-title": "Opravdu chcete smazat '{{name}}'?", "delete-chat-text": "Všechny zprávy chatu budou ztraceny", "delete-chat-confirm": "Ano, smazat", - "action-approval-required": "Vyžadováno schválení akce", "approve": "Schválit", "deny": "Zamítnout", - "processing": "Zpracovává se...", "approved": "Hotovo", - "denied": "Zamítnuto", "error": "Selhalo", - "thinking": "Přemýšlím...", - "rename-chat-title": "Přejmenovat tento chat", - "main-title": "Ahoj! Jsem váš AI asistent" + "thinking": "Přemýšlím..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Navrhnout pravidla alarmů", diff --git a/ui-ngx/src/assets/locale/locale.constant-da_DK.json b/ui-ngx/src/assets/locale/locale.constant-da_DK.json index 33d38f576a..965db063d3 100644 --- a/ui-ngx/src/assets/locale/locale.constant-da_DK.json +++ b/ui-ngx/src/assets/locale/locale.constant-da_DK.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurér med AI", - "follow-up-prompt-placeholder": "Svar...", - "sub-title": "Jeg kan hjælpe dig med at opsætte og administrere dine enheder, dashboards, beregnede felter, alarmregler og notifikationer — beskriv blot, hvad du har brug for, så klarer jeg resten.", "new-chat": "Ny chat", - "no-chats": "Ingen chats endnu", "today": "I dag", "yesterday": "I går", "last-7-days": "Sidste 7 dage", @@ -703,20 +700,12 @@ "delete-chat-title": "Er du sikker på, at du vil slette '{{name}}'?", "delete-chat-text": "Alle chatbeskeder vil gå tabt", "delete-chat-confirm": "Ja, slet", - "action-approval-required": "Godkendelse af handlingen påkrævet", "approve": "Godkend", - "approve-all": "Godkend alle yderligere handlinger", "deny": "Afvis", - "processing": "Behandler...", "approved": "Færdig", - "denied": "Afvist", "error": "Mislykkedes", "thinking": "Tænker...", - "connection-lost": "Forbindelsen til AI-assistenten blev afbrudt. Genopretter forbindelsen...", - "reconnect-failed": "Kunne ikke genoprette forbindelsen til AI-assistenten. Åbn chatten igen for at se svaret.", - "rename-chat-title": "Omdøb denne chat", - "export-chat": "Eksportér chat", - "main-title": "Hej! Jeg er din AI-assistent" + "export-chat": "Eksportér chat" }, "alarm": { "alarm": "Alarm", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Træk og slip din konto-legitimationsfil" }, "solution-creator": { - "ai-solution-creator": "AI-løsningsbygger", "describe-solution-you-want": "Beskriv den løsning, du vil lave", - "enter-your-prompt": "Indtast din prompt", "target": "Mål", "install-solution": "Installér", - "solution-overview": "Løsningsoversigt: {{ name }}", - "dashboards-overview": "Dashboardoversigt: {{ name }}", - "entity-profile": "Entitetsprofil", - "entity-profiles": "Entitetsprofiler", - "name": "Navn", - "iam": "IAM", - "iam-full": "Identitets- og adgangsstyring", - "table-view": "Tabel", - "schema-view": "Skema", - "iam-info": "IAM-info", "operation": { "C": "Opret", "R": "Læs", "U": "Opdatér", "D": "Slet" }, - "alarm-info": "Alarmoplysninger", "description": "Beskrivelse", - "data": "Data", - "entity-info": "Entitetsoplysninger", - "calculated-field-info": "Oplysninger om beregnet felt", - "field-type": "Felttype", - "scope": "Omfang", "delete-alarm-title": "Slet denne foreslåede alarm?", "delete-alarm-text": "Denne alarm, der er foreslået ud fra din beskrivelse, bliver ikke føjet til den foreslåede opbygning af løsningen.
    Du kan altid redigere eller oprette alarmer igen manuelt senere. Denne handling kan ikke fortrydes.", - "basic-mode": "Grundlæggende", - "advanced-mode": "Avanceret", "create-solution": "Opret løsning", "go-dashboard-manager": "Næste: Dashboarddesign", - "success-generate-title": "Løsningen er klar!", - "success-generate-sub-title": "Du kan installere den på din konto ved at klikke på knappen nedenfor", - "success-generate-install-title": "Løsningen er installeret!", - "success-generate-install-sub-title": "For at redigere løsningen skal du først afinstallere den eksisterende instans", - "main-title": "Hej! Jeg er din AI-assistent", - "sub-title": "Jeg hjælper dig med at omsætte dine krav til en fuldt funktionel IoT-løsning.\nBeskriv bare, hvad du vil opnå, så klarer jeg resten.", - "solutions": "Løsninger", "new-solution": "Ny løsning", "uninstall-solution": "Afinstallér", "uninstall-solution-dialog-title": "Er du sikker på, at du vil afinstallere ‘{{ name }}’?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "Alle dine data vil gå tabt", "delete-solution-confirm": "Ja, slet", "copy-solution": "Kopiér løsning", - "expand-sidebar": "Udvid sidepanel", - "collapse-sidebar": "Skjul sidepanel", "solution-id": "Løsnings-ID", "solution-id-required": "Løsnings-ID er påkrævet", - "rename-solution-title": "Omdøb denne løsning", - "generate-again": "Generér igen", "skip-interview": "Spring interview over", "update-solution": "Opdatér løsning", "finish-edit": "Afslut redigering", @@ -11300,8 +11258,6 @@ "water-metering": "Vandmåling", "coffee-machine-monitoring": "Overvågning af kaffemaskiner", "fleet-geofencing": "Geofencing af flåder", - "more-examples": "Flere eksempler", - "hide": "Skjul", "solution-info": "Løsningsinfo", "solution-info-with-name": "Løsningsinfo: {{ name }}", "status": "Status", @@ -11314,14 +11270,8 @@ "info": "Info", "main-dashboard": "Hoveddashboard", "view-as": "Vis som {{ name }}", - "generated-by-calculated-field-name": "Genereret af det beregnede felt ‘{{ name }}’", "estimate-wait-time": "Anslået ventetid er ~{{ time }}", - "analyzing-your-request": "Analyserer din anmodning...", "condition": "Betingelse", - "installing": "Installerer løsning...", - "step-architecture-design": "Arkitekturdesign", - "step-dashboard-design": "Dashboarddesign", - "step-solution-installation": "Løsningsinstallation", "step-reading-device-data": "Læser enhedsdata…", "step-analyzing-telemetry-attributes": "Analyserer telemetri og attributter…", "step-selecting-widgets": "Vælger widgets til dine data…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "Opbygger alarmregler…", "step-loading-assembling-dashboards": "Samler dashboards…", "step-loading-preparing-states": "Forbereder tilstande…", - "step-loading-initializing-solution": "Initialiserer løsning…", - "ai-credits": "AI-kreditter", - "ai-credits-update": "Skift plan", - "ai-credits-usage": "AI-kreditter: {{ used }} af {{ max }} brugt", - "ai-credits-description": "Du har brugt {{ used }} af dine {{ max }} AI-kreditter denne måned. Grænsen nulstilles den {{ date }}. Kontakt din systemadministrator for at øge din grænse for AI-kreditter." + "step-loading-initializing-solution": "Initialiserer løsning…" }, "markdown": { "edit": "Redigér", @@ -13783,11 +13729,6 @@ "disk-warning-text": "Lav diskplads. Frigør eller udvid diskpladsen for at undgå datatab.", "disk-critical-text": "Kritisk lav diskplads. Frigør eller udvid diskpladsen for at undgå datatab." }, - "cluster-info": { - "service-id": "Service-id", - "service-type": "Servicetype", - "no-data": "Ingen data" - }, "transport-messages": { "title": "Transportbeskeder", "info": "Alle beskeder der kommer fra enheder" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "Ingen dashboards er blevet vist endnu" }, "configured-features": { - "title": "Konfigurerede funktioner", - "info": "Status for funktioner, der kræver konfiguration", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funktionen er konfigureret.\nKlik for at opsætte", "feature-not-configured": "Funktionen er ikke konfigureret.\nKlik for at opsætte" }, - "version-info": { - "title": "Version", - "contact-us": "Kontakt os", - "current-version": "Nuværende version", - "current": "Aktuel", - "available-version": "Tilgængelig version", - "available": "Tilgængelig", - "upgrade": "Opgradér", - "version-is-up-to-date": "Du har den nyeste version" - }, - "license-info": { - "title": "Licensinfo", - "view-all": "Se alle", - "license-portal": "Licensportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Enheder", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Aktiver", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrationer", - "community-support": "Fællesskabssupport", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Ubegrænsede datapunkter og beskeder", - "unlimited-api-calls": "Ubegrænsede API-kald" - }, "usage-info": { "title": "Forbrug", "entities": "Entiteter", diff --git a/ui-ngx/src/assets/locale/locale.constant-de_DE.json b/ui-ngx/src/assets/locale/locale.constant-de_DE.json index ddd4ddff2f..08f58a3e87 100644 --- a/ui-ngx/src/assets/locale/locale.constant-de_DE.json +++ b/ui-ngx/src/assets/locale/locale.constant-de_DE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Mit KI konfigurieren", - "follow-up-prompt-placeholder": "Antworten...", - "sub-title": "Ich helfe Ihnen beim Einrichten und Verwalten Ihrer Geräte, Dashboards, berechneten Felder, Alarmregeln und Benachrichtigungen – beschreiben Sie einfach, was Sie brauchen, und ich erledige den Rest.", "new-chat": "Neuer Chat", - "no-chats": "Noch keine Chats", "today": "Heute", "yesterday": "Gestern", "last-7-days": "Letzte 7 Tage", @@ -703,18 +700,12 @@ "delete-chat-title": "Möchten Sie '{{name}}' wirklich löschen?", "delete-chat-text": "Alle Chatnachrichten gehen verloren", "delete-chat-confirm": "Ja, löschen", - "action-approval-required": "Genehmigung der Aktion erforderlich", "approve": "Genehmigen", - "approve-all": "Alle weiteren Aktionen genehmigen", "deny": "Ablehnen", - "processing": "Wird verarbeitet...", "approved": "Fertig", - "denied": "Abgelehnt", "error": "Fehlgeschlagen", "thinking": "Denke nach...", - "rename-chat-title": "Diesen Chat umbenennen", - "export-chat": "Chat exportieren", - "main-title": "Hallo! Ich bin Ihr KI-Assistent" + "export-chat": "Chat exportieren" }, "alarm": { "alarm": "Alarm", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Ziehen Sie Ihre Kontozugangsdaten-Datei hierher" }, "solution-creator": { - "ai-solution-creator": "KI-Lösungsersteller", "describe-solution-you-want": "Beschreiben Sie die Lösung, die Sie erstellen möchten", - "enter-your-prompt": "Prompt eingeben", "target": "Ziel", "install-solution": "Installieren", - "solution-overview": "Lösungsübersicht: {{ name }}", - "dashboards-overview": "Dashboards-Übersicht: {{ name }}", - "entity-profile": "Entitätsprofil", - "entity-profiles": "Entitätsprofile", - "name": "Name", - "iam": "IAM", - "iam-full": "Identitäts- und Zugriffsverwaltung", - "table-view": "Tabelle", - "schema-view": "Schema", - "iam-info": "IAM-Info", "operation": { "C": "Erstellen", "R": "Lesen", "U": "Speichern", "D": "Löschen" }, - "alarm-info": "Alarm-Info", "description": "Beschreibung", - "data": "Daten", - "entity-info": "Entitäts-Info", - "calculated-field-info": "Info zum berechneten Feld", - "field-type": "Feldtyp", - "scope": "Bereich", "delete-alarm-title": "Diesen vorgeschlagenen Alarm löschen?", "delete-alarm-text": "Dieser Alarm, der auf Grundlage Ihrer Beschreibung vorgeschlagen wurde, wird nicht in die vorgeschlagene Lösung aufgenommen.
    Sie können Alarme später jederzeit manuell bearbeiten oder neu erstellen. Diese Aktion kann nicht rückgängig gemacht werden.", - "basic-mode": "Einfach", - "advanced-mode": "Erweitert", "create-solution": "Lösung erstellen", "go-dashboard-manager": "Weiter: Dashboard-Design", - "success-generate-title": "Lösung ist bereit!", - "success-generate-sub-title": "Sie können sie über die Schaltfläche unten in Ihrem Konto installieren", - "success-generate-install-title": "Lösung installiert!", - "success-generate-install-sub-title": "Um die Lösung zu bearbeiten, deinstallieren Sie bitte zuerst die vorhandene Instanz", - "main-title": "Hallo! Ich bin Ihr KI-Assistent", - "sub-title": "Ich helfe Ihnen, Ihre Anforderungen in eine voll funktionsfähige IoT-Lösung zu verwandeln.\nBeschreiben Sie einfach, was Sie erreichen möchten, und ich erledige den Rest.", - "solutions": "Lösungen", "new-solution": "Neue Lösung", "uninstall-solution": "Deinstallieren", "uninstall-solution-dialog-title": "Möchten Sie ‘{{ name }}’ wirklich deinstallieren?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Alle Ihre Daten gehen verloren", "delete-solution-confirm": "Ja, löschen", "copy-solution": "Lösung kopieren", - "expand-sidebar": "Seitenleiste ausklappen", - "collapse-sidebar": "Seitenleiste einklappen", "solution-id": "Lösungs-ID", "solution-id-required": "Lösungs-ID ist erforderlich", - "rename-solution-title": "Diese Lösung umbenennen", - "generate-again": "Erneut generieren", "skip-interview": "Interview überspringen", "update-solution": "Lösung aktualisieren", "finish-edit": "Bearbeitung abschließen", @@ -11298,8 +11258,6 @@ "water-metering": "Wasserzählung", "coffee-machine-monitoring": "Kaffeemaschinen-Überwachung", "fleet-geofencing": "Flotten-Geofencing", - "more-examples": "Weitere Beispiele", - "hide": "Ausblenden", "solution-info": "Lösungsinfo", "solution-info-with-name": "Lösungsinfo: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Haupt-Dashboard", "view-as": "Anzeigen als {{ name }}", - "generated-by-calculated-field-name": "Erzeugt durch berechnetes Feld ‘{{ name }}’", "estimate-wait-time": "Geschätzte Wartezeit ca. {{ time }}", - "analyzing-your-request": "Anfrage wird analysiert...", "condition": "Bedingung", - "installing": "Lösung wird installiert...", - "step-architecture-design": "Architekturentwurf", - "step-dashboard-design": "Dashboard-Entwurf", - "step-solution-installation": "Lösungsinstallation", "step-reading-device-data": "Gerätedaten werden gelesen…", "step-analyzing-telemetry-attributes": "Telemetrie und Attribute werden analysiert…", "step-selecting-widgets": "Widgets für Ihre Daten werden ausgewählt…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarmregeln werden erstellt…", "step-loading-assembling-dashboards": "Dashboards werden zusammengestellt…", "step-loading-preparing-states": "Zustände werden vorbereitet…", - "step-loading-initializing-solution": "Lösung wird initialisiert…", - "ai-credits": "KI-Credits", - "ai-credits-update": "Speichern", - "ai-credits-usage": "KI-Credits: {{ used }} von {{ max }} verbraucht", - "ai-credits-description": "Sie haben diesen Monat {{ used }} von {{ max }} AI Credits verbraucht. Das Limit wird am {{ date }} zurückgesetzt. Um Ihr AI-Credit-Kontingent zu erhöhen, wenden Sie sich bitte an Ihren Systemadministrator." + "step-loading-initializing-solution": "Lösung wird initialisiert…" }, "markdown": { "edit": "Bearbeiten", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Wenig Festplattenspeicher. Bereinigen oder erweitern Sie den Speicherplatz, um Datenverlust zu vermeiden.", "disk-critical-text": "Kritisch wenig Festplattenspeicher. Bereinigen oder erweitern Sie den Speicherplatz, um Datenverlust zu vermeiden." }, - "cluster-info": { - "service-id": "Dienst-ID", - "service-type": "Diensttyp", - "no-data": "Keine Daten" - }, "transport-messages": { "title": "Transportnachrichten", "info": "Alle Nachrichten, die von Geräten empfangen wurden" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Noch keine zuletzt angesehenen Dashboards" }, "configured-features": { - "title": "Konfigurierte Funktionen", - "info": "Status der Funktionen, die eine Konfiguration erfordern", - "white-labeling-feature": "White-Labeling", - "email-feature": "E-Mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funktion ist konfiguriert.\nZum Einrichten klicken", "feature-not-configured": "Funktion ist nicht konfiguriert.\nZum Einrichten klicken" }, - "version-info": { - "title": "Version", - "contact-us": "Kontaktieren Sie uns", - "current-version": "Aktuelle Version", - "current": "Aktuell", - "available-version": "Verfügbare Version", - "available": "Verfügbar", - "upgrade": "Upgrade durchführen", - "version-is-up-to-date": "Version ist aktuell" - }, - "license-info": { - "title": "Lizenzinformationen", - "view-all": "Alle anzeigen", - "license-portal": "Lizenzportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Geräte", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrationen", - "community-support": "Community-Support", - "white-labeling": "White-Labeling", - "unlimited-datapoints-and-messages": "Unbegrenzte Datenpunkte und Nachrichten", - "unlimited-api-calls": "Unbegrenzte API-Aufrufe" - }, "usage-info": { "title": "Nutzung", "entities": "Entitäten", diff --git a/ui-ngx/src/assets/locale/locale.constant-el_GR.json b/ui-ngx/src/assets/locale/locale.constant-el_GR.json index bc7726c070..2e7d5f6b36 100644 --- a/ui-ngx/src/assets/locale/locale.constant-el_GR.json +++ b/ui-ngx/src/assets/locale/locale.constant-el_GR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Διαμόρφωση με τη βοήθεια AI", - "follow-up-prompt-placeholder": "Απάντηση...", - "sub-title": "Μπορώ να σας βοηθήσω να ρυθμίσετε και να διαχειριστείτε τις συσκευές, τους πίνακες ελέγχου, τα υπολογιζόμενα πεδία, τους κανόνες συναγερμών και τις ειδοποιήσεις σας — απλώς περιγράψτε τι χρειάζεστε και θα αναλάβω τα υπόλοιπα.", "new-chat": "Νέα συνομιλία", - "no-chats": "Δεν υπάρχουν ακόμη συνομιλίες", "today": "Σήμερα", "yesterday": "Χθες", "last-7-days": "Τελευταίες 7 ημέρες", @@ -703,20 +700,12 @@ "delete-chat-title": "Είστε βέβαιοι ότι θέλετε να διαγράψετε το '{{name}}';", "delete-chat-text": "Όλα τα μηνύματα της συνομιλίας θα χαθούν", "delete-chat-confirm": "Ναι, διαγραφή", - "action-approval-required": "Απαιτείται έγκριση ενέργειας", "approve": "Έγκριση", - "approve-all": "Έγκριση όλων των επόμενων ενεργειών", "deny": "Απόρριψη", - "processing": "Επεξεργασία...", "approved": "Ολοκληρώθηκε", - "denied": "Απορρίφθηκε", "error": "Απέτυχε", "thinking": "Σκέφτομαι...", - "connection-lost": "Η σύνδεση με τον βοηθό AI χάθηκε. Επανασύνδεση...", - "reconnect-failed": "Δεν ήταν δυνατή η επανασύνδεση με τον βοηθό AI. Ανοίξτε ξανά τη συνομιλία για να δείτε την απάντησή του.", - "rename-chat-title": "Μετονομασία αυτής της συνομιλίας", - "export-chat": "Εξαγωγή συνομιλίας", - "main-title": "Γεια σας! Είμαι ο βοηθός AI σας" + "export-chat": "Εξαγωγή συνομιλίας" }, "alarm": { "alarm": "Συναγερμός", @@ -11247,47 +11236,20 @@ "select-recaptcha-enterprise-service-account-file": "Σύρετε και αποθέστε το αρχείο διαπιστευτηρίων του λογαριασμού σας" }, "solution-creator": { - "ai-solution-creator": "Δημιουργός λύσεων AI", "describe-solution-you-want": "Περιγράψτε τη λύση που θέλετε να δημιουργήσετε", - "enter-your-prompt": "Εισαγάγετε την προτροπή σας", "target": "Στόχος", "install-solution": "Εγκατάσταση", - "solution-overview": "Επισκόπηση λύσης: {{ name }}", - "dashboards-overview": "Επισκόπηση πινάκων ελέγχου: {{ name }}", - "entity-profile": "Προφίλ οντότητας", - "entity-profiles": "Προφίλ οντοτήτων", - "name": "Όνομα", - "iam": "IAM", - "iam-full": "Διαχείριση ταυτοτήτων και πρόσβασης", - "table-view": "Πίνακας", - "schema-view": "Σχήμα", - "iam-info": "Πληροφορίες IAM", "operation": { "C": "Δημιουργία", "R": "Ανάγνωση", "U": "Ενημέρωση", "D": "Διαγραφή" }, - "alarm-info": "Πληροφορίες συναγερμού", "description": "Περιγραφή", - "data": "Δεδομένα", - "entity-info": "Πληροφορίες οντότητας", - "calculated-field-info": "Πληροφορίες υπολογιζόμενου πεδίου", - "field-type": "Τύπος πεδίου", - "scope": "Εμβέλεια", "delete-alarm-title": "Διαγραφή αυτού του προτεινόμενου συναγερμού;", "delete-alarm-text": "Αυτός ο συναγερμός, που προτάθηκε με βάση την περιγραφή σας, δεν θα προστεθεί στη δημιουργία της προτεινόμενης λύσης.
    Μπορείτε πάντα να επεξεργαστείτε ή να δημιουργήσετε ξανά συναγερμούς χειροκίνητα αργότερα. Αυτή η ενέργεια δεν μπορεί να αναιρεθεί.", - "basic-mode": "Βασική", - "advanced-mode": "Για προχωρημένους", "create-solution": "Δημιουργία λύσης", "go-dashboard-manager": "Επόμενο: Σχεδίαση πίνακα ελέγχου", - "success-generate-title": "Η λύση είναι έτοιμη!", - "success-generate-sub-title": "Μπορείτε να την εγκαταστήσετε στον λογαριασμό σας κάνοντας κλικ στο παρακάτω κουμπί", - "success-generate-install-title": "Η λύση εγκαταστάθηκε!", - "success-generate-install-sub-title": "Για να επεξεργαστείτε τη λύση, απεγκαταστήστε πρώτα την υπάρχουσα εγκατάσταση", - "main-title": "Γεια σας! Είμαι ο βοηθός AI σας", - "sub-title": "Σας βοηθώ να μετατρέψετε τις απαιτήσεις σας σε μια πλήρως λειτουργική λύση IoT.\nΑρκεί να περιγράψετε τι θέλετε να επιτύχετε και θα αναλάβω τα υπόλοιπα.", - "solutions": "Λύσεις", "new-solution": "Νέα λύση", "uninstall-solution": "Απεγκατάσταση", "uninstall-solution-dialog-title": "Είστε βέβαιοι ότι θέλετε να απεγκαταστήσετε τη λύση ‘{{ name }}’;", @@ -11297,12 +11259,8 @@ "delete-solution-text": "Όλα τα δεδομένα σας θα χαθούν", "delete-solution-confirm": "Ναι, διαγραφή", "copy-solution": "Αντιγραφή λύσης", - "expand-sidebar": "Ανάπτυξη πλευρικής γραμμής", - "collapse-sidebar": "Σύμπτυξη πλευρικής γραμμής", "solution-id": "ID λύσης", "solution-id-required": "Απαιτείται ID λύσης", - "rename-solution-title": "Μετονομασία αυτής της λύσης", - "generate-again": "Νέα δημιουργία", "skip-interview": "Παράλειψη συνέντευξης", "update-solution": "Ενημέρωση λύσης", "finish-edit": "Ολοκλήρωση επεξεργασίας", @@ -11312,8 +11270,6 @@ "water-metering": "Μέτρηση νερού", "coffee-machine-monitoring": "Παρακολούθηση μηχανής καφέ", "fleet-geofencing": "Γεωπερίφραξη στόλου", - "more-examples": "Περισσότερα παραδείγματα", - "hide": "Απόκρυψη", "solution-info": "Πληροφορίες λύσης", "solution-info-with-name": "Πληροφορίες λύσης: {{ name }}", "status": "Κατάσταση", @@ -11326,14 +11282,8 @@ "info": "Πληροφορίες", "main-dashboard": "Κύριος πίνακας ελέγχου", "view-as": "Προβολή ως {{ name }}", - "generated-by-calculated-field-name": "Δημιουργήθηκε από το υπολογιζόμενο πεδίο ‘{{ name }}’", "estimate-wait-time": "Ο εκτιμώμενος χρόνος αναμονής είναι ~{{ time }}", - "analyzing-your-request": "Ανάλυση του αιτήματός σας...", "condition": "Συνθήκη", - "installing": "Εγκατάσταση λύσης...", - "step-architecture-design": "Σχεδιασμός αρχιτεκτονικής", - "step-dashboard-design": "Σχεδιασμός πίνακα ελέγχου", - "step-solution-installation": "Εγκατάσταση λύσης", "step-reading-device-data": "Ανάγνωση δεδομένων συσκευής…", "step-analyzing-telemetry-attributes": "Ανάλυση τηλεμετρίας και χαρακτηριστικών…", "step-selecting-widgets": "Επιλογή widget για τα δεδομένα σας…", @@ -11365,11 +11315,7 @@ "step-loading-building-alarm-rules": "Δημιουργία κανόνων συναγερμών…", "step-loading-assembling-dashboards": "Συναρμολόγηση πινάκων ελέγχου…", "step-loading-preparing-states": "Προετοιμασία καταστάσεων…", - "step-loading-initializing-solution": "Αρχικοποίηση λύσης…", - "ai-credits": "Πιστώσεις AI", - "ai-credits-update": "Αλλαγή προγράμματος", - "ai-credits-usage": "Πιστώσεις AI: χρησιμοποιήθηκαν {{ used }} από {{ max }}", - "ai-credits-description": "Έχετε χρησιμοποιήσει {{ used }} από τις {{ max }} πιστώσεις AI σας αυτόν τον μήνα. Το όριο μηδενίζεται στις {{ date }}. Για να αυξήσετε το διαθέσιμο όριο πιστώσεων AI, επικοινωνήστε με τον διαχειριστή του συστήματός σας." + "step-loading-initializing-solution": "Αρχικοποίηση λύσης…" }, "markdown": { "edit": "Επεξεργασία", @@ -13795,11 +13741,6 @@ "disk-warning-text": "Ο χώρος στον δίσκο είναι χαμηλός. Για να αποφύγετε την απώλεια δεδομένων, ελευθερώστε ή επεκτείνετε τον χώρο στον δίσκο.", "disk-critical-text": "Κρίσιμα χαμηλός χώρος στον δίσκο. Για να αποφύγετε την απώλεια δεδομένων, ελευθερώστε ή επεκτείνετε τον χώρο στον δίσκο." }, - "cluster-info": { - "service-id": "Αναγνωριστικό υπηρεσίας", - "service-type": "Τύπος υπηρεσίας", - "no-data": "Δεν υπάρχουν δεδομένα" - }, "transport-messages": { "title": "Μηνύματα μεταφοράς", "info": "Όλα τα μηνύματα που ελήφθησαν από συσκευές" @@ -13838,41 +13779,9 @@ "no-last-viewed-dashboards": "Δεν έχετε προβάλει ακόμη πίνακες ελέγχου" }, "configured-features": { - "title": "Διαμορφωμένες δυνατότητες", - "info": "Κατάσταση δυνατοτήτων που απαιτούν ρύθμιση", - "white-labeling-feature": "White labeling", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Η δυνατότητα έχει ρυθμιστεί.\nΚάντε κλικ για ρύθμιση", "feature-not-configured": "Η δυνατότητα δεν έχει ρυθμιστεί.\nΚάντε κλικ για ρύθμιση" }, - "version-info": { - "title": "Έκδοση", - "contact-us": "Επικοινωνήστε μαζί μας", - "current-version": "Τρέχουσα έκδοση", - "current": "Τρέχουσα", - "available-version": "Διαθέσιμη έκδοση", - "available": "Διαθέσιμη", - "upgrade": "Αναβάθμιση", - "version-is-up-to-date": "Η έκδοση είναι ενημερωμένη" - }, - "license-info": { - "title": "Πληροφορίες άδειας χρήσης", - "view-all": "Προβολή όλων", - "license-portal": "Πύλη αδειών χρήσης", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Συσκευές", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Περιουσιακά στοιχεία", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Πίνακες ελέγχου", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Ενσωματώσεις", - "community-support": "Υποστήριξη κοινότητας", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Απεριόριστα σημεία δεδομένων και μηνύματα", - "unlimited-api-calls": "Απεριόριστες κλήσεις API" - }, "usage-info": { "title": "Χρήση", "entities": "Οντότητες", 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 ef0d8fb31f..f635c9a9f4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -703,7 +703,6 @@ "done": "Done", "skip": "Skip", "you-said": "You said", - "skipped": "You skipped", "none": "None", "no-answer": "No answer", "your-answer": "Your answer", @@ -713,7 +712,6 @@ "ai-assistant": "AI Assistant", "configure-with-ai": "Configure with AI", "follow-up-prompt-placeholder": "Add something, or ask what happened…", - "sub-title": "I can help you set up and manage your Devices, Dashboards, Calculated Fields, Alarm Rules, and Notifications — just describe what you need, and I'll handle the rest.", "split-view": "Split view", "loading-chat": "Opening the chat…", "ai-assistant-cue": "AI Assistant · {{ cue }}", @@ -729,7 +727,6 @@ }, "back-to-panel": "Back to the panel", "new-chat": "New chat", - "no-chats": "No chats yet", "today": "Today", "yesterday": "Yesterday", "last-7-days": "Last 7 days", @@ -737,16 +734,11 @@ "delete-chat-title": "Are you sure you want to delete '{{name}}'?", "delete-chat-text": "All chat messages will be lost", "delete-chat-confirm": "Yes, delete", - "action-approval-required": "Action approval required", "approve": "Approve", - "approve-all": "Approve all further actions", "deny": "Deny", - "processing": "Processing...", "approved": "Done", - "denied": "Denied", "error": "Failed", "thinking": "Thinking...", - "connection-lost": "Connection to the AI Assistant was lost. Reconnecting...", "stopped-after": "{ count, plural, =1 {You stopped this reply after 1 step. Nothing more was done.} other {You stopped this reply after # steps. Nothing more was done.} }", "stopped-before": "You stopped this reply before any step. Nothing was done.", "notice": { @@ -757,7 +749,6 @@ "rate-limited": "Too many requests for a moment. Send the message again in a minute.", "credits-used-up": "The AI credits are used up. Sending resumes when the limit resets." }, - "reconnect-failed": "Couldn't reconnect to the AI Assistant. Reopen the chat to see its reply.", "ask-the-assistant": "Ask the AI Assistant", "send": "Send", "new-line": "New line", @@ -853,7 +844,6 @@ "read-attributes": "Read the attributes of {{entity}}", "read-attributes-scope": "Read the {{scope}} of {{entity}}", "discover-attribute-keys": "Listed the attribute keys used by the devices of {{entity}}", - "save-attributes": "Saved {{count}} {{scope}} on {{entity}}", "delete-attributes": "Deleted {{scope}} from {{entity}}", "scope": { "server": "server attributes", @@ -873,7 +863,8 @@ "clear": "{ count, plural, =1 {Cleared an alarm} other {Cleared # alarms} }", "assign": "{ count, plural, =1 {Assigned an alarm} other {Assigned # alarms} }", "unassign": "{ count, plural, =1 {Unassigned an alarm} other {Unassigned # alarms} }", - "comment": "{ count, plural, =1 {Commented on an alarm} other {Commented on # alarms} }" + "comment": "{ count, plural, =1 {Commented on an alarm} other {Commented on # alarms} }", + "other": "{ count, plural, =1 {Updated an alarm} other {Updated # alarms} }" }, "alarms-done": "Done", "alarms-skipped": "Already in that state", @@ -1092,7 +1083,16 @@ "add-scada-connectors": "Drew {{count}} pipe lines on {{entity}}", "update-widget": "Updated the widget '{{name}}' of {{entity}}", "read-widget": "Read the widget '{{name}}'", - "place-widgets": "Placed {{count}} widgets on {{entity}}", + "place-widgets": "Placed {count} { count, plural, =1 {widget} other {widgets} } on {entity}", + "save-attributes": { + "server": "Saved {count} { count, plural, =1 {server attribute} other {server attributes} } on {entity}", + "shared": "Saved {count} { count, plural, =1 {shared attribute} other {shared attributes} } on {entity}", + "client": "Saved {count} { count, plural, =1 {client attribute} other {client attributes} } on {entity}", + "other": "Saved {count} { count, plural, =1 {attribute} other {attributes} } on {entity}" + }, + "widget-size": "{{width}} × {{height}}", + "widget-size-at": "{{width}} × {{height}} at {{col}}, {{row}}", + "widget-placed": "{{name}} · {{width}} × {{height}} at {{col}}, {{row}}", "set-html-page": "Had the state '{{state}}' of {{entity}} written as an HTML page", "read-html-page": "Read the HTML page of the state '{{state}}' of {{entity}}", "delete": "Deleted {{entity}}", @@ -1124,7 +1124,56 @@ "notification-rule": "notification rule", "notification-target": "recipient list", "notification-template": "notification template", - "entity": "entity" + "entity": "entity", + "tenant": "tenant", + "tenant-profile": "tenant profile", + "customer": "customer", + "user": "user", + "device": "device", + "device-profile": "device profile", + "asset-profile": "asset profile", + "asset": "asset", + "entity-view": "entity view", + "edge": "edge", + "rule-chain": "rule chain", + "rule-node": "rule node", + "dashboard": "dashboard", + "alarm": "alarm", + "entity-group": "entity group", + "api-usage-state": "api usage state", + "widget-type": "widget", + "widgets-bundle": "widgets bundle", + "converter": "data converter", + "integration": "integration", + "scheduler-event": "scheduler event", + "blob-entity": "blob entity", + "report-template": "report template", + "report": "report", + "role": "role", + "group-permission": "group permission", + "tb-resource": "resource", + "ota-package": "ota package", + "job": "task", + "rpc": "rpc", + "queue": "queue", + "queue-stats": "queue statistics", + "notification": "notification", + "notification-request": "notification request", + "domain": "domain", + "oauth2-client": "oauth 2.0 client", + "mobile-app": "mobile application", + "mobile-app-bundle": "mobile bundle", + "admin-settings": "admin settings", + "ai-model": "ai model", + "secret": "secret storage", + "api-key": "api key", + "agent": "agent", + "agent-profile": "agent profile", + "agent-application": "application", + "agent-app-profile": "application profile", + "agent-app-event": "agent app event", + "agent-app-unit": "agent app unit", + "agent-bulk-action": "bulk action" }, "states": "States", "aliases": "Entity aliases", @@ -2175,7 +2224,7 @@ "title": "AI credits", "used": "{{used}} of {{max}} used this month", "resets": "Resets on {{date}}.", - "left": "{{left}} credits left", + "left": "{left} { count, plural, =1 {credit} other {credits} } left", "none-left": "No credits left", "aria": "AI credits: {{used}} of {{max}} used this month" }, @@ -2233,12 +2282,12 @@ "license-text-old": "You have reached the maximum {{entities}} allowed by your subscription plan. You can upgrade the plan to raise your limits.", "feature-title": "{{feature}} not included in your plan", "feature": { - "white-labeling": "White-labeling", + "white-labeling": "White labeling", "integrations": "Integrations", "scheduler": "Scheduler", "reporting": "Reports" }, - "white-labeling-text": "With White-labeling, your brand replaces ThingsBoard's on the login page, in the mail you send and on every page your customers work in.", + "white-labeling-text": "With White labeling, your brand replaces ThingsBoard's on the login page, in the mail you send and on every page your customers work in.", "pack-text": "It comes with the Professional Pack. Request access and your system administrator gets your request.", "license-required": "License required", "request": "Request a higher limit", @@ -2389,8 +2438,7 @@ "title": "Set up the CLI", "run-install": "Run the install command", "accept-folder": "Accept the project folder", - "accept-before": "Press Enter at “Project folder” to keep ", - "accept-after": " Press Enter again when the setup offers to connect.", + "accept": "Press Enter at “Project folder” to keep {{folder}} Press Enter again when the setup offers to connect.", "paste-url": "Paste your ThingsBoard URL", "url": "URL", "copy-url": "Copy the url", @@ -2399,8 +2447,7 @@ "open-api-keys": "Open API keys", "start-agent": "Start your agent", "start-agent-text": "Press Enter at “Start Claude Code now?” or “Start Antigravity now?” Your agent opens in the project folder with the ThingsBoard skills loaded.", - "both-agents": "With both agents installed, the setup first asks which one to set up. Pick ", - "both-agents-or": " or ", + "both-agents": "With both agents installed, the setup first asks which one to set up. Pick {{claude}} or {{antigravity}}", "come-back-folder": "To come back later, start your agent from the project folder:", "agent-start": "Start your agent in a new folder", "agent-send": "Send the setup prompt", @@ -2410,8 +2457,7 @@ "agent-key": "Create an API key for the Connect page", "agent-key-text": "Click “Create an API key”. Under API keys, click Manage, then + Generate, and paste the key on the page. The key stays out of the chat.", "agent-restart": "Restart your agent", - "restart-before": "Skills load only when an agent starts. Type ", - "restart-after": " in Claude Code, or close Antigravity, then run:", + "restart": "Skills load only when an agent starts. Type {{exit}} in Claude Code, or close Antigravity, then run:", "come-back": "To come back later, start your agent from the same folder." }, "describe": { @@ -2467,7 +2513,14 @@ "one-line-each": "One line each", "wrap-long-lines": "Wrap long lines", "download": "Download", - "download-file": "Download {{name}}" + "download-file": "Download {{name}}", + "label": { + "terminal": "Terminal", + "log": "Log", + "diff": "Diff", + "text": "Text", + "config": "Config" + } }, "task": { "connect-device": { @@ -2791,7 +2844,7 @@ "operation-upgrade": "Upgrade", "operation-delete": "Delete", "operation-cancel": "Cancel the running operation", - "operation-upgrade agent": "Upgrade the agent", + "operation-upgrade-agent": "Upgrade the agent", "edgeTemplateRoot-yes": "Yes", "autoAssign-yes": "Yes", "autoAssign-no": "No", @@ -2859,7 +2912,7 @@ "not-acknowledged": "Not acknowledged", "since": "since {{time}}", "cleared-at": "cleared {{time}}", - "installs": "{{count}} installs", + "installs": "{shown} { count, plural, =1 {install} other {installs} }", "open-on-iot-hub": "Open on IoT Hub, in a new tab", "open-new-tab": "Open the {{type}} in a new tab", "open-type": "Open {{type}}", @@ -2872,9 +2925,6 @@ }, "summary": { "made": "What this run made or changed", - "open-dashboard": "Open dashboard", - "alarm-rule": "Alarm rule", - "calculated-field": "Calculated field", "entities": "{ count, plural, =1 {1 entity} other {# entities} }", "alarm-rules": "Alarm rules", "more": "{{count}} more", @@ -2901,10 +2951,7 @@ "text": "Text", "file": "File" }, - "rename-chat-title": "Rename this chat", "export-chat": "Export chat", - "main-title": "Hello! I'm your AI Assistant", - "chat": "Chat", "chats": "Chats", "open-chats": "Open chats", "close-chats": "Close chats", @@ -2914,7 +2961,6 @@ "chats-show-here": "Your chats show here.", "chat-actions": "Chat actions", "chat-title": "Chat title", - "in-progress": "In progress", "prompt-placeholder": "Ask about your devices, dashboards and alarms, or connect something new…", "what-to-work-on": "What would you like to work on?", "pinned": "Pinned", @@ -3004,7 +3050,7 @@ "status-tip-nodata": "Nothing arrived from the device yet", "status-tip-running": "In progress", "status-tip-error": "The run stopped", - "waiting-one": "Open {{ title }}, it needs you", + "waiting-one": "Open {{ title }}, which is waiting for you", "waiting-one-tip": "{{ title }}: {{ status }}", "waiting-many": "{ count, plural, =1 {1 chat needs you} other {# chats need you} }", "running-one-tip": "{{ title }} is running", @@ -3014,8 +3060,8 @@ "auto-approve": "Auto-approve", "auto-approve-on": "On", "auto-approve-off": "Off", - "auto-approve-text": "Actions go ahead without waiting for your Approve.", - "auto-approve-new-chat-text": "In the new chat, actions go ahead without waiting for your Approve.", + "auto-approve-text": "Actions go ahead without waiting for your approval.", + "auto-approve-new-chat-text": "In the new chat, actions go ahead without waiting for your approval.", "run-again": "Run again", "fact": { "pages": "{ count, plural, =1 {1 page} other {# pages} }", @@ -3027,7 +3073,6 @@ "start-suggestion": "Connect a temperature sensor and chart its readings on a dashboard", "suggestion-sr": "Suggestion: {{text}}. Tab accepts it.", "file": { - "meta": "{{label}} · {{lines}} lines · {{size}}", "lines": "{ count, plural, =1 {1 line} other {# lines} }", "open": "Open the file", "wrap": "Wrap long lines", @@ -3038,7 +3083,6 @@ "download-png": "Download as PNG", "png-failed": "The PNG could not be made from this image.", "find": "Find in file", - "match-of": "{{at}} of {{count}}", "no-matches": "No matches", "previous-match": "Previous match (Shift+Enter)", "next-match": "Next match (Enter)", @@ -3050,8 +3094,6 @@ "light": "Light", "line": "Line {{from}}", "lines-range": "Lines {{from}}–{{to}}", - "line-marked": "Line {{from}} marked", - "lines-marked": "Lines {{from}}–{{to}} marked", "clear": "Clear", "ask-about": "Ask about them", "files": "Files in this chat", @@ -3079,7 +3121,7 @@ "svg-broken": "This SVG does not draw. Edit opens its source." }, "welcome": { - "placeholder": "Ask anything or describe what to set up...", + "placeholder": "Ask anything or describe what to set up…", "edges": { "title": "Ask about your edges", "title-customer": "Ask about this customer's edges", @@ -4241,7 +4283,6 @@ "steps": "{ count, plural, =1 {1 step} other {# steps} }", "done-of": "{{done}} of {{count}}", "change": "Change the plan", - "change-prompt": "Change the plan: ", "change-ask": "Change the plan.", "you": "You", "needs": { @@ -4253,7 +4294,7 @@ "run": "Run", "run-step-by-step": "Run step by step", "run-auto": "Run with auto-approve", - "run-tip": "Each change waits for your Approve", + "run-tip": "Each change waits for your approval", "run-auto-tip": "Changes are made as the plan says. Every action still shows, and Stop halts the run.", "run-prompt": "Run the plan.", "leave-out": "Leave out step {{number}}: {{text}}" @@ -4263,6 +4304,45 @@ "text": "The rest of this run waits for your yes at each step. Let it run through? Every action still shows here, and Stop halts the run.", "approve-rest": "Auto-approve the rest", "keep-asking": "Keep asking" + }, + "list": { + "pair": "{{first}} and {{second}}", + "more": "{{first}}, {{rest}}" + }, + "part": { + "html": "HTML", + "css": "CSS", + "js": "JavaScript", + "resources": "resources", + "settingsForm": "settings form", + "dataKeySettingsForm": "data key settings form", + "latestDataKeySettingsForm": "latest data key settings form", + "defaultConfig": "default configuration", + "svg": "SVG", + "metadata": "metadata", + "functions": "functions", + "behavior": "behaviors", + "properties": "properties" + }, + "part-title": { + "html": "HTML", + "css": "CSS", + "js": "JavaScript", + "resources": "Resources", + "settingsForm": "Settings form", + "dataKeySettingsForm": "Data key settings form", + "latestDataKeySettingsForm": "Latest data key settings form", + "defaultConfig": "Default configuration", + "svg": "SVG", + "metadata": "Metadata", + "functions": "Functions", + "behavior": "Behaviors", + "properties": "Properties" + }, + "duration": { + "seconds": "{{seconds}} s", + "minutes": "{{minutes}} min", + "minutes-seconds": "{{minutes}} min {{seconds}} s" } }, "alarm": { @@ -8911,7 +8991,6 @@ "all": "All", "mine": "Mine", "add-rule": "Add alarm rule", - "no-active": "No active alarms.", "no-rules": "No alarm rules yet. Add a rule to see its alarms here.", "how-rules-work": "How alarm rules work", "no-alarms-yet": "No alarms yet", @@ -9120,8 +9199,8 @@ "skipped": "Skipped", "skip": "Skip", "undo-skip": "Undo skip", - "finished": "Every step is done. Install's Features takes this place.", - "finished-skipped": "{{count}} skipped. Install's Features takes this place; each stays there to set up.", + "finished": "Every step is done. The Install card takes this place.", + "finished-skipped": "{{count}} skipped. The Install card takes this place, and each skipped feature stays there to set up.", "tenant": { "title": "Create a tenant and its administrator", "text": "A tenant owns devices and assets; its administrators create and manage its devices, assets, customers and dashboards.", @@ -9206,10 +9285,10 @@ "gb": "{{value}} GB", "at": "{{name}} at {{value}}%", "at-on": "{{name}} at {{value}}% on {{services}}", - "and": " and ", + "and": "{{first}} and {{second}}", "now": "now", "chart": "CPU, RAM and disk over the last hour", - "service-id": "Service id", + "service-id": "Service ID", "service-type": "Service type" }, "list": { @@ -9248,7 +9327,7 @@ "offer-title": "Ask from Home", "offer-text": "Ask a question, or have it connect a device, build a dashboard or add an alarm rule.", "offer-action": "Ask", - "offer-key": "to ask" + "offer-key": "{{key}} to ask" }, "customize": { "title": "Customize Home", @@ -13078,8 +13157,12 @@ "copy-public-link": "Copy link" }, "report-template": { + "ai-reload-title": "The AI changed this template", + "ai-reload-text": "Load the AI's version? Your unsaved changes will be lost.", + "ai-reload-keep": "Keep my changes", + "ai-reload-confirm": "Load the AI's version", "ai-assistant-title": "Ask about this report template", - "ai-assistant-initial-prompt-placeholder": "Describe the report you need...", + "ai-assistant-initial-prompt-placeholder": "Describe the report you need…", "ai-assistant-suggestion": "Is this report ready to send?", "ai-assistant-example-fleet-label": "Weekly fleet report", "ai-assistant-example-fleet-message": "Build a weekly PDF report of my devices: a chart of their main readings over the previous week, a table of their latest values and their critical alarms.", @@ -14883,7 +14966,7 @@ }, "widget": { "ai-assistant-title": "Ask about this widget", - "ai-assistant-initial-prompt-placeholder": "Describe the widget you need...", + "ai-assistant-initial-prompt-placeholder": "Describe the widget you need…", "ai-assistant-suggestion": "Check this widget for errors.", "ai-assistant-example-explain-label": "Explain this widget", "ai-assistant-example-explain-message": "Explain what this widget does: its data, settings and how it renders.", @@ -15453,8 +15536,6 @@ "attribute": "attribute", "calculated-fields": "Calculated fields", "calculates": "Calculates", - "close": "Close the panel", - "condition": "Condition", "creating": "Creating…", "dashboards": "Dashboards", "data": "Data", @@ -15465,7 +15546,7 @@ "estimate-solution": "About a minute", "about-seconds": "About {{count}} seconds", "about-minutes": "About {{count}} minutes", - "credits": "{{credits}} credits", + "credits": "{credits} { count, plural, =1 {credit} other {credits} }", "get-started": "Get started", "installed": "Solution installed", "installed-line": "{ entities, plural, =1 {1 entity} other {# entities} } · { dashboards, plural, =1 {1 dashboard} other {# dashboards} } · live on simulated data", @@ -15475,8 +15556,6 @@ "json-applied": "Applied", "json-discarded": "Your JSON changes were discarded.", "json-tip": "View as JSON", - "download": "Download", - "download-file": "Download {{name}}", "view-json": "View", "keys": "{ count, plural, =1 {1 key} other {# keys} }", "list": "List", @@ -15501,8 +15580,6 @@ "relations": "{ count, plural, =1 {1 relation} other {# relations} }", "relations-tab": "Relations", "remove": "Remove", - "resize": "Resize the panel", - "resize-hint": "Drag to resize; double-click to reset", "role": "Role", "roles": "Roles", "schema": "Schema", @@ -15546,7 +15623,7 @@ "example-tip": "Puts the example in the composer", "limits": "Nothing is created in your tenant until you approve the design and install it.", "what-is-solution": "What is a solution?", - "about-title": "ThingsBoard Solution Creator", + "about-title": "AI solution creator", "about-design-title": "A description becomes a design", "about-design": "The AI drafts the architecture: device and asset profiles, relations, roles, calculated fields and alarm rules.", "about-approve-title": "You approve each step", @@ -15555,7 +15632,7 @@ "about-dashboards": "Every role gets its dashboard; simulated devices feed them until yours connect.", "about-installed-title": "Installed in your tenant", "about-installed": "Real entities, yours to keep: edit the design or uninstall it from the solution's chat.", - "issues-lead": "{ count, plural, =1 {One item needs a look} other {# items need a look} } after the install:", + "issues-lead": "{ count, plural, =1 {One item needs your attention} other {# items need your attention} } after the install:", "issues-tip-lead": "Tip:", "issues-tip": "open the Solution view to see what went wrong with each, or ask about it here.", "assumptions": "Assumptions", @@ -15584,47 +15661,20 @@ "closing-simulated": "A real device takes over a simulated one when it connects.", "work-reading": "Reading your description", "work-thinking": "Working on the design", - "ai-solution-creator": "AI solution creator", "describe-solution-you-want": "Describe a solution you want to make", - "enter-your-prompt": "Enter your prompt", "target": "Target", "install-solution": "Install", - "solution-overview": "Solution overview: {{ name }}", - "dashboards-overview": "Dashboards overview: {{ name }}", - "entity-profile": "Entity profile", - "entity-profiles": "Entity profiles", - "name": "Name", - "iam": "IAM", - "iam-full": "Identity and Access Management", - "table-view": "Table", - "schema-view": "Schema", - "iam-info": "IAM info", "operation": { "C": "Create", "R": "Read", "U": "Update", "D": "Delete" }, - "alarm-info": "Alarm info", "description": "Description", - "data": "Data", - "entity-info": "Entity info", - "calculated-field-info": "Calculated field info", - "field-type": "Field type", - "scope": "Scope", "delete-alarm-title": "Delete this suggested alarm?", "delete-alarm-text": "This alarm, suggested based on your description, won't be added to the proposed solution build.
    You can always edit or recreate alarms manually later. This action cannot be undone.", - "basic-mode": "Basic", - "advanced-mode": "Advanced", "create-solution": "Create solution", "go-dashboard-manager": "Next: Dashboard Design", - "success-generate-title": "Solution is ready!", - "success-generate-sub-title": "You can install it on your account by clicking the button below", - "success-generate-install-title": "Solution installed!", - "success-generate-install-sub-title": "To edit the solution, please uninstall the existing instance first", - "main-title": "Hello! I'm your AI Assistant", - "sub-title": "I help you transform your requirements into a fully functional IoT solution.\nJust describe what you want to achieve, and I'll handle the rest.", - "solutions": "Solutions", "new-solution": "New solution", "uninstall-solution": "Uninstall", "uninstall-solution-dialog-title": "Are you sure you want to uninstall ‘{{ name }}’?", @@ -15634,12 +15684,8 @@ "delete-solution-text": "All your data will be lost", "delete-solution-confirm": "Yes, delete", "copy-solution": "Copy solution", - "expand-sidebar": "Expand sidebar", - "collapse-sidebar": "Collapse sidebar", "solution-id": "Solution id", "solution-id-required": "Solution id is required", - "rename-solution-title": "Rename this solution", - "generate-again": "Generate again", "regenerate": "Regenerate", "skip-interview": "Skip interview", "update-solution": "Update solution", @@ -15650,8 +15696,6 @@ "water-metering": "Water Metering", "coffee-machine-monitoring": "Coffee Machine Monitoring", "fleet-geofencing": "Fleet Geofencing", - "more-examples": "More examples", - "hide": "Hide", "solution-info": "Solution info", "solution-info-with-name": "Solution info: {{ name }}", "status": "Status", @@ -15664,14 +15708,8 @@ "info": "Info", "main-dashboard": "Main dashboard", "view-as": "View as {{ name }}", - "generated-by-calculated-field-name": "Generated by ‘{{ name }}’ calculated field", "estimate-wait-time": "Estimated wait time is ~{{ time }}", - "analyzing-your-request": "Analyzing your request...", "condition": "Condition", - "installing": "Installing solution...", - "step-architecture-design": "Architecture Design", - "step-dashboard-design": "Dashboard Design", - "step-solution-installation": "Solution Installation", "step-reading-device-data": "Reading device data…", "step-analyzing-telemetry-attributes": "Analyzing telemetry & attributes…", "step-selecting-widgets": "Selecting widgets for your data…", @@ -15703,11 +15741,7 @@ "step-loading-building-alarm-rules": "Building alarm rules…", "step-loading-assembling-dashboards": "Assembling dashboards…", "step-loading-preparing-states": "Preparing states…", - "step-loading-initializing-solution": "Initializing solution…", - "ai-credits": "AI Credits", - "ai-credits-update": "Update", - "ai-credits-usage": "AI Credits: {{ used }} of {{ max }} used", - "ai-credits-description": "You've used {{ used }} of your {{ max }} AI Credits this month. Limit resets on {{ date }}. To increase your AI Credit allowance, please contact your system administrator." + "step-loading-initializing-solution": "Initializing solution…" }, "markdown": { "edit": "Edit", @@ -18146,11 +18180,6 @@ "disk-warning-text": "Running low on disk space. To avoid data loss, free up or expand the disk space.", "disk-critical-text": "Critically low disk space. To avoid data loss, free up or expand the disk space." }, - "cluster-info": { - "service-id": "Service id", - "service-type": "Service type", - "no-data": "No data" - }, "transport-messages": { "title": "Transport messages", "info": "All the messages that came from devices" @@ -18189,41 +18218,9 @@ "no-last-viewed-dashboards": "No last viewed dashboards yet" }, "configured-features": { - "title": "Configured features", - "info": "Status of features that require configuration", - "white-labeling-feature": "White labeling", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Feature is configured.\nClick to setup", "feature-not-configured": "Feature is not configured.\nClick to setup" }, - "version-info": { - "title": "Version", - "contact-us": "Contact us", - "current-version": "Current version", - "current": "Current", - "available-version": "Available version", - "available": "Available", - "upgrade": "Upgrade", - "version-is-up-to-date": "Version is up to date" - }, - "license-info": { - "title": "License info", - "view-all": "View all", - "license-portal": "License portal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Devices", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrations", - "community-support": "Community support", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Unlimited datapoints and messages", - "unlimited-api-calls": "Unlimited API calls" - }, "usage-info": { "title": "Usage", "entities": "Entities", diff --git a/ui-ngx/src/assets/locale/locale.constant-es_ES.json b/ui-ngx/src/assets/locale/locale.constant-es_ES.json index ae7b5bc9f7..d7359fb705 100644 --- a/ui-ngx/src/assets/locale/locale.constant-es_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-es_ES.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurar con IA", - "follow-up-prompt-placeholder": "Responder...", - "sub-title": "Puedo ayudarte a configurar y gestionar tus dispositivos, paneles, campos calculados, reglas de alarma y notificaciones; solo describe lo que necesitas y yo me encargo del resto.", "new-chat": "Nuevo chat", - "no-chats": "Aún no hay chats", "today": "Hoy", "yesterday": "Ayer", "last-7-days": "Últimos 7 días", @@ -703,18 +700,12 @@ "delete-chat-title": "¿Estás seguro de que quieres eliminar '{{name}}'?", "delete-chat-text": "Se perderán todos los mensajes del chat", "delete-chat-confirm": "Sí, eliminar", - "action-approval-required": "Se requiere aprobación de la acción", "approve": "Aprobar", - "approve-all": "Aprobar todas las acciones siguientes", "deny": "Denegar", - "processing": "Procesando...", "approved": "Hecho", - "denied": "Denegado", "error": "Falló", "thinking": "Pensando...", - "rename-chat-title": "Cambiar el nombre de este chat", - "export-chat": "Exportar chat", - "main-title": "¡Hola! Soy tu asistente de IA" + "export-chat": "Exportar chat" }, "alarm": { "alarm": "Alarma", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Arrastra y suelta tu archivo de credenciales de cuenta" }, "solution-creator": { - "ai-solution-creator": "Creador de soluciones con IA", "describe-solution-you-want": "Describe la solución que deseas crear", - "enter-your-prompt": "Ingresa tu instrucción", "target": "Destino", "install-solution": "Instalar", - "solution-overview": "Resumen de la solución: {{ name }}", - "dashboards-overview": "Resumen de tableros: {{ name }}", - "entity-profile": "Perfil de entidad", - "entity-profiles": "Perfiles de entidad", - "name": "Nombre", - "iam": "IAM", - "iam-full": "Gestión de identidades y accesos", - "table-view": "Tabla", - "schema-view": "Esquema", - "iam-info": "Información de IAM", "operation": { "C": "Crear", "R": "Leer", "U": "Modificar", "D": "Eliminar" }, - "alarm-info": "Información de la alarma", "description": "Descripción", - "data": "Datos", - "entity-info": "Información de la entidad", - "calculated-field-info": "Información del campo calculado", - "field-type": "Tipo de campo", - "scope": "Ámbito", "delete-alarm-title": "¿Eliminar esta alarma sugerida?", "delete-alarm-text": "Esta alarma, sugerida a partir de tu descripción, no se agregará a la compilación de la solución propuesta.
    Siempre puedes editar o volver a crear las alarmas manualmente más tarde. Esta acción no se puede deshacer.", - "basic-mode": "Básico", - "advanced-mode": "Avanzado", "create-solution": "Crear solución", "go-dashboard-manager": "Siguiente: Diseño del tablero", - "success-generate-title": "¡La solución está lista!", - "success-generate-sub-title": "Puedes instalarla en tu cuenta haciendo clic en el botón de abajo", - "success-generate-install-title": "¡Solución instalada!", - "success-generate-install-sub-title": "Para editar la solución, primero desinstala la instancia existente", - "main-title": "¡Hola! Soy tu asistente de IA", - "sub-title": "Te ayudo a transformar tus requisitos en una solución IoT totalmente funcional.\nSolo describe lo que deseas lograr y yo me encargo del resto.", - "solutions": "Soluciones", "new-solution": "Nueva solución", "uninstall-solution": "Desinstalar", "uninstall-solution-dialog-title": "¿Estás seguro de que deseas desinstalar ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Se perderán todos tus datos", "delete-solution-confirm": "Sí, eliminar", "copy-solution": "Copiar solución", - "expand-sidebar": "Expandir barra lateral", - "collapse-sidebar": "Contraer barra lateral", "solution-id": "ID de la solución", "solution-id-required": "Se requiere el ID de la solución", - "rename-solution-title": "Cambiar el nombre de esta solución", - "generate-again": "Generar de nuevo", "skip-interview": "Omitir entrevista", "update-solution": "Actualizar solución", "finish-edit": "Finalizar edición", @@ -11298,8 +11258,6 @@ "water-metering": "Medición de agua", "coffee-machine-monitoring": "Monitoreo de máquinas de café", "fleet-geofencing": "Geocercas para flotas", - "more-examples": "Más ejemplos", - "hide": "Ocultar", "solution-info": "Información de la solución", "solution-info-with-name": "Información de la solución: {{ name }}", "status": "Estado", @@ -11312,14 +11270,8 @@ "info": "Información", "main-dashboard": "Tablero principal", "view-as": "Ver como {{ name }}", - "generated-by-calculated-field-name": "Generado por el campo calculado ‘{{ name }}’", "estimate-wait-time": "El tiempo de espera estimado es de ~{{ time }}", - "analyzing-your-request": "Analizando tu solicitud...", "condition": "Condición", - "installing": "Instalando la solución...", - "step-architecture-design": "Diseño de la arquitectura", - "step-dashboard-design": "Diseño del tablero", - "step-solution-installation": "Instalación de la solución", "step-reading-device-data": "Leyendo los datos del dispositivo…", "step-analyzing-telemetry-attributes": "Analizando telemetría y atributos…", "step-selecting-widgets": "Seleccionando widgets para tus datos…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construyendo reglas de alarma…", "step-loading-assembling-dashboards": "Ensamblando tableros…", "step-loading-preparing-states": "Preparando estados…", - "step-loading-initializing-solution": "Inicializando la solución…", - "ai-credits": "Créditos de IA", - "ai-credits-update": "Guardar cambios", - "ai-credits-usage": "Créditos de IA: {{ used }} de {{ max }} utilizados", - "ai-credits-description": "Has utilizado {{ used }} de tus {{ max }} créditos de IA este mes. El límite se restablece el {{ date }}. Para aumentar tu asignación de créditos de IA, contacta a tu administrador del sistema." + "step-loading-initializing-solution": "Inicializando la solución…" }, "markdown": { "edit": "Editar", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Espacio en disco reducido. Para evitar pérdida de datos, libere o expanda el espacio.", "disk-critical-text": "Espacio en disco críticamente bajo. Para evitar pérdida de datos, libere o expanda el espacio." }, - "cluster-info": { - "service-id": "ID del servicio", - "service-type": "Tipo de servicio", - "no-data": "Sin datos" - }, "transport-messages": { "title": "Mensajes de transporte", "info": "Todos los mensajes que llegaron desde los dispositivos" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Aún no se han visualizado tableros recientemente" }, "configured-features": { - "title": "Características configuradas", - "info": "Estado de las características que requieren configuración", - "white-labeling-feature": "Marca blanca", - "email-feature": "Correo electrónico", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "La característica está configurada.\nHaz clic para configurarla", "feature-not-configured": "La característica no está configurada.\nHaz clic para configurarla" }, - "version-info": { - "title": "Versión", - "contact-us": "Contáctenos", - "current-version": "Versión actual", - "current": "Actual", - "available-version": "Versión disponible", - "available": "Disponible", - "upgrade": "Actualizar versión", - "version-is-up-to-date": "La versión está actualizada" - }, - "license-info": { - "title": "Información de licencia", - "view-all": "Ver todo", - "license-portal": "Portal de licencias", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivos", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Activos", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Tableros", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraciones", - "community-support": "Soporte comunitario", - "white-labeling": "Marca blanca", - "unlimited-datapoints-and-messages": "Puntos de datos y mensajes ilimitados", - "unlimited-api-calls": "Llamadas API ilimitadas" - }, "usage-info": { "title": "Uso", "entities": "Entidades", diff --git a/ui-ngx/src/assets/locale/locale.constant-fa_IR.json b/ui-ngx/src/assets/locale/locale.constant-fa_IR.json index d639e90e19..69a9e18198 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fa_IR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fa_IR.json @@ -88,10 +88,7 @@ }, "ai-assistant": { "configure-with-ai": "پیکربندی با هوش مصنوعی", - "follow-up-prompt-placeholder": "پاسخ...", - "sub-title": "می‌توانم در راه‌اندازی و مدیریت دستگاه‌ها، داشبوردها، فیلدهای محاسبه‌شده، قوانین هشدار و اعلان‌های شما کمک کنم — کافی است آنچه نیاز دارید را توضیح دهید و بقیه را به من بسپارید.", "new-chat": "گفت‌وگوی جدید", - "no-chats": "هنوز گفت‌وگویی وجود ندارد", "today": "امروز", "yesterday": "دیروز", "last-7-days": "7 روز گذشته", @@ -99,16 +96,11 @@ "delete-chat-title": "آیا مطمئن هستید که می‌خواهید '{{name}}' را حذف کنید؟", "delete-chat-text": "همه پیام‌های گفت‌وگو از دست خواهند رفت", "delete-chat-confirm": "بله، حذف کن", - "action-approval-required": "تأیید اقدام لازم است", "approve": "تأیید", "deny": "رد", - "processing": "در حال پردازش...", "approved": "انجام شد", - "denied": "رد شد", "error": "ناموفق", - "thinking": "در حال فکر کردن...", - "rename-chat-title": "تغییر نام این گفت‌وگو", - "main-title": "سلام! من دستیار هوش مصنوعی شما هستم" + "thinking": "در حال فکر کردن..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "پیشنهاد قوانین هشدار", diff --git a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json index a9b8fd88ee..87b321a794 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurer avec l’IA", - "follow-up-prompt-placeholder": "Répondre...", - "sub-title": "Je peux vous aider à configurer et à gérer vos appareils, tableaux de bord, champs calculés, règles d’alarme et notifications — décrivez simplement ce dont vous avez besoin et je m’occupe du reste.", "new-chat": "Nouveau chat", - "no-chats": "Aucun chat pour le moment", "today": "Aujourd’hui", "yesterday": "Hier", "last-7-days": "7 derniers jours", @@ -703,18 +700,12 @@ "delete-chat-title": "Voulez-vous vraiment supprimer '{{name}}' ?", "delete-chat-text": "Tous les messages du chat seront perdus", "delete-chat-confirm": "Oui, supprimer", - "action-approval-required": "Approbation de l’action requise", "approve": "Approuver", - "approve-all": "Approuver toutes les actions suivantes", "deny": "Refuser", - "processing": "Traitement en cours...", "approved": "Terminé", - "denied": "Refusé", "error": "Échoué", "thinking": "Réflexion...", - "rename-chat-title": "Renommer ce chat", - "export-chat": "Exporter le chat", - "main-title": "Bonjour ! Je suis votre assistant IA" + "export-chat": "Exporter le chat" }, "alarm": { "alarm": "Alarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Déposez ici le fichier d’identifiants de compte" }, "solution-creator": { - "ai-solution-creator": "Créateur de solution IA", "describe-solution-you-want": "Décrivez une solution que vous souhaitez créer", - "enter-your-prompt": "Saisissez votre invite", "target": "Cible", "install-solution": "Installer", - "solution-overview": "Aperçu de la solution : {{ name }}", - "dashboards-overview": "Aperçu des tableaux de bord : {{ name }}", - "entity-profile": "Profil d’entité", - "entity-profiles": "Profils d’entité", - "name": "Nom", - "iam": "IAM", - "iam-full": "Gestion des identités et des accès", - "table-view": "Tableau", - "schema-view": "Schéma", - "iam-info": "Informations IAM", "operation": { "C": "Créer", "R": "Lire", "U": "Mettre à jour", "D": "Supprimer" }, - "alarm-info": "Informations sur l’alarme", "description": "Description", - "data": "Données", - "entity-info": "Informations sur l’entité", - "calculated-field-info": "Informations sur le champ calculé", - "field-type": "Type de champ", - "scope": "Portée", "delete-alarm-title": "Supprimer cette alarme suggérée ?", "delete-alarm-text": "Cette alarme, suggérée en fonction de votre description, ne sera pas ajoutée à la version de solution proposée.
    Vous pourrez toujours modifier ou recréer des alarmes manuellement plus tard. Cette action est irréversible.", - "basic-mode": "Basique", - "advanced-mode": "Avancé", "create-solution": "Créer une solution", "go-dashboard-manager": "Suivant : Conception du tableau de bord", - "success-generate-title": "La solution est prête !", - "success-generate-sub-title": "Vous pouvez l’installer sur votre compte en cliquant sur le bouton ci-dessous", - "success-generate-install-title": "Solution installée !", - "success-generate-install-sub-title": "Pour modifier la solution, veuillez d’abord désinstaller l’instance existante", - "main-title": "Bonjour ! Je suis votre assistant IA", - "sub-title": "Je vous aide à transformer vos besoins en une solution IoT entièrement fonctionnelle.\nDécrivez simplement ce que vous souhaitez accomplir, et je m’occupe du reste.", - "solutions": "Solutions", "new-solution": "Nouvelle solution", "uninstall-solution": "Désinstaller", "uninstall-solution-dialog-title": "Êtes-vous sûr de vouloir désinstaller « {{ name }} » ?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Toutes vos données seront perdues", "delete-solution-confirm": "Oui, supprimer", "copy-solution": "Copier la solution", - "expand-sidebar": "Développer la barre latérale", - "collapse-sidebar": "Réduire la barre latérale", "solution-id": "ID de la solution", "solution-id-required": "L’ID de solution est requis", - "rename-solution-title": "Renommer cette solution", - "generate-again": "Générer à nouveau", "skip-interview": "Passer l’entretien", "update-solution": "Mettre à jour la solution", "finish-edit": "Terminer la modification", @@ -11298,8 +11258,6 @@ "water-metering": "Comptage d’eau", "coffee-machine-monitoring": "Surveillance des machines à café", "fleet-geofencing": "Géorepérage de flotte", - "more-examples": "Plus d’exemples", - "hide": "Masquer", "solution-info": "Informations sur la solution", "solution-info-with-name": "Informations sur la solution : {{ name }}", "status": "Statut", @@ -11312,14 +11270,8 @@ "info": "Infos", "main-dashboard": "Tableau de bord principal", "view-as": "Afficher en tant que {{ name }}", - "generated-by-calculated-field-name": "Généré par le champ calculé « {{ name }} »", "estimate-wait-time": "Le temps d’attente estimé est d’environ {{ time }}", - "analyzing-your-request": "Analyse de votre demande...", "condition": "Condition", - "installing": "Installation de la solution...", - "step-architecture-design": "Conception de l’architecture", - "step-dashboard-design": "Conception du tableau de bord", - "step-solution-installation": "Installation de la solution", "step-reading-device-data": "Lecture des données de l’appareil…", "step-analyzing-telemetry-attributes": "Analyse de la télémétrie et des attributs…", "step-selecting-widgets": "Sélection des widgets pour vos données…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construction des règles d’alarme…", "step-loading-assembling-dashboards": "Assemblage des tableaux de bord…", "step-loading-preparing-states": "Préparation des états…", - "step-loading-initializing-solution": "Initialisation de la solution…", - "ai-credits": "Crédits IA", - "ai-credits-update": "Mettre à jour", - "ai-credits-usage": "Crédits IA : {{ used }} sur {{ max }} utilisés", - "ai-credits-description": "Vous avez utilisé {{ used }} sur {{ max }} crédits IA ce mois-ci. La limite se réinitialise le {{ date }}. Pour augmenter votre allocation de crédits IA, veuillez contacter votre administrateur système." + "step-loading-initializing-solution": "Initialisation de la solution…" }, "markdown": { "edit": "Modifier", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Espace disque faible. Pour éviter une perte de données, libérez ou augmentez l’espace disque.", "disk-critical-text": "Espace disque critique. Pour éviter une perte de données, libérez ou augmentez l’espace disque." }, - "cluster-info": { - "service-id": "ID du service", - "service-type": "Type de service", - "no-data": "Aucune donnée" - }, "transport-messages": { "title": "Messages de transport", "info": "Tous les messages provenant des appareils" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Aucun tableau de bord consulté récemment" }, "configured-features": { - "title": "Fonctionnalités configurées", - "info": "Statut des fonctionnalités nécessitant une configuration", - "white-labeling-feature": "Marque blanche", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Fonctionnalité configurée.\nCliquez pour configurer", "feature-not-configured": "Fonctionnalité non configurée.\nCliquez pour configurer" }, - "version-info": { - "title": "Version", - "contact-us": "Contactez-nous", - "current-version": "Version actuelle", - "current": "Actuelle", - "available-version": "Version disponible", - "available": "Disponible", - "upgrade": "Mettre à niveau", - "version-is-up-to-date": "La version est à jour" - }, - "license-info": { - "title": "Informations sur la licence", - "view-all": "Voir tout", - "license-portal": "Portail des licences", - "devices-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Appareils", - "assets-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Ressources", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Tableaux de bord", - "integrations-info": "{count} / { max, plural, =0 {∞} one {#} other {#} } Intégrations", - "community-support": "Support communautaire", - "white-labeling": "Marque blanche", - "unlimited-datapoints-and-messages": "Points de données et messages illimités", - "unlimited-api-calls": "Appels API illimités" - }, "usage-info": { "title": "Utilisation", "entities": "Entités", diff --git a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json index 56de7f7880..25d23470af 100644 --- a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json +++ b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI से कॉन्फ़िगर करें", - "follow-up-prompt-placeholder": "उत्तर दें...", - "sub-title": "मैं आपके डिवाइस, डैशबोर्ड, कैलक्युलेटेड फ़ील्ड, अलार्म नियम और सूचनाओं को सेट अप और प्रबंधित करने में आपकी मदद कर सकता हूँ — बस बताइए आपको क्या चाहिए, बाकी मैं संभाल लूँगा।", "new-chat": "नई चैट", - "no-chats": "अभी तक कोई चैट नहीं", "today": "आज", "yesterday": "कल", "last-7-days": "पिछले 7 दिन", @@ -703,17 +700,11 @@ "delete-chat-title": "क्या आप वाकई '{{name}}' को हटाना चाहते हैं?", "delete-chat-text": "सभी चैट संदेश खो जाएँगे", "delete-chat-confirm": "हाँ, हटाएँ", - "action-approval-required": "कार्रवाई के लिए स्वीकृति आवश्यक", "approve": "स्वीकृत करें", - "approve-all": "आगे की सभी कार्रवाइयों को स्वीकृत करें", "deny": "अस्वीकार करें", - "processing": "प्रोसेस हो रहा है...", "approved": "हो गया", - "denied": "अस्वीकृत", "error": "विफल", "thinking": "सोच रहा हूँ...", - "connection-lost": "AI असिस्टेंट से कनेक्शन टूट गया। फिर से कनेक्ट हो रहा है...", - "reconnect-failed": "AI असिस्टेंट से फिर से कनेक्ट नहीं हो सका। उसका उत्तर देखने के लिए चैट फिर से खोलें।", "ask-the-assistant": "AI असिस्टेंट से पूछें", "send": "भेजें", "new-line": "नई पंक्ति", @@ -740,9 +731,7 @@ "text": "टेक्स्ट", "file": "फ़ाइल" }, - "rename-chat-title": "इस चैट का नाम बदलें", - "export-chat": "चैट एक्सपोर्ट करें", - "main-title": "नमस्ते! मैं आपका AI असिस्टेंट हूँ" + "export-chat": "चैट एक्सपोर्ट करें" }, "alarm": { "alarm": "अलार्म", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "अपनी खाता क्रेडेंशियल्स फ़ाइल ड्रैग और ड्रॉप करें" }, "solution-creator": { - "ai-solution-creator": "AI समाधान निर्माता", "describe-solution-you-want": "वह समाधान बताएँ जो आप बनाना चाहते हैं", - "enter-your-prompt": "अपना प्रॉम्प्ट दर्ज करें", "target": "लक्ष्य", "install-solution": "इंस्टॉल करें", - "solution-overview": "समाधान का अवलोकन: {{ name }}", - "dashboards-overview": "डैशबोर्डों का अवलोकन: {{ name }}", - "entity-profile": "एंटिटी प्रोफ़ाइल", - "entity-profiles": "एंटिटी प्रोफ़ाइल", - "name": "नाम", - "iam": "IAM", - "iam-full": "पहचान और ऐक्सेस प्रबंधन", - "table-view": "टेबल", - "schema-view": "स्कीमा", - "iam-info": "IAM जानकारी", "operation": { "C": "बनाएँ", "R": "पढ़ें", "U": "अपडेट करें", "D": "हटाएँ" }, - "alarm-info": "अलार्म जानकारी", "description": "विवरण", - "data": "डेटा", - "entity-info": "एंटिटी जानकारी", - "calculated-field-info": "कैलक्युलेटेड फ़ील्ड जानकारी", - "field-type": "फ़ील्ड प्रकार", - "scope": "स्कोप", "delete-alarm-title": "क्या आप वाकई इस सुझाए गए अलार्म को हटाना चाहते हैं?", "delete-alarm-text": "आपके विवरण के आधार पर सुझाया गया यह अलार्म प्रस्तावित समाधान बिल्ड में नहीं जोड़ा जाएगा।
    आप बाद में कभी भी अलार्मों को मैन्युअल रूप से संपादित कर सकते हैं या फिर से बना सकते हैं। यह क्रिया पूर्ववत नहीं की जा सकती।", - "basic-mode": "बेसिक", - "advanced-mode": "उन्नत", "create-solution": "समाधान बनाएँ", "go-dashboard-manager": "अगला: डैशबोर्ड डिज़ाइन", - "success-generate-title": "समाधान तैयार है!", - "success-generate-sub-title": "नीचे दिए गए बटन पर क्लिक करके आप इसे अपने खाते में इंस्टॉल कर सकते हैं", - "success-generate-install-title": "समाधान इंस्टॉल हो गया!", - "success-generate-install-sub-title": "समाधान को संपादित करने के लिए, कृपया पहले मौजूदा इंस्टेंस को अनइंस्टॉल करें", - "main-title": "नमस्ते! मैं आपका AI असिस्टेंट हूँ", - "sub-title": "मैं आपकी आवश्यकताओं को पूरी तरह से काम करने वाले IoT समाधान में बदलने में आपकी मदद करता हूँ।\nबस बताएँ कि आप क्या हासिल करना चाहते हैं, बाकी मैं संभाल लूँगा।", - "solutions": "समाधान", "new-solution": "नया समाधान", "uninstall-solution": "अनइंस्टॉल करें", "uninstall-solution-dialog-title": "क्या आप वाकई ‘{{ name }}’ को अनइंस्टॉल करना चाहते हैं?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "आपका सारा डेटा खो जाएगा", "delete-solution-confirm": "हाँ, हटाएँ", "copy-solution": "समाधान कॉपी करें", - "expand-sidebar": "साइडबार विस्तृत करें", - "collapse-sidebar": "साइडबार संकुचित करें", "solution-id": "समाधान ID", "solution-id-required": "समाधान ID आवश्यक है", - "rename-solution-title": "इस समाधान का नाम बदलें", - "generate-again": "फिर से जनरेट करें", "skip-interview": "इंटरव्यू छोड़ें", "update-solution": "समाधान अपडेट करें", "finish-edit": "संपादन पूरा करें", @@ -11338,8 +11296,6 @@ "water-metering": "जल मीटरिंग", "coffee-machine-monitoring": "कॉफ़ी मशीन मॉनिटरिंग", "fleet-geofencing": "फ़्लीट जियोफ़ेंसिंग", - "more-examples": "और उदाहरण", - "hide": "छिपाएँ", "solution-info": "समाधान की जानकारी", "solution-info-with-name": "समाधान की जानकारी: {{ name }}", "status": "स्थिति", @@ -11352,14 +11308,8 @@ "info": "जानकारी", "main-dashboard": "मुख्य डैशबोर्ड", "view-as": "{{ name }} के रूप में देखें", - "generated-by-calculated-field-name": "‘{{ name }}’ कैलक्युलेटेड फ़ील्ड द्वारा जनरेट किया गया", "estimate-wait-time": "अनुमानित प्रतीक्षा समय ~{{ time }} है", - "analyzing-your-request": "आपके अनुरोध का विश्लेषण किया जा रहा है...", "condition": "शर्त", - "installing": "समाधान इंस्टॉल किया जा रहा है...", - "step-architecture-design": "आर्किटेक्चर डिज़ाइन", - "step-dashboard-design": "डैशबोर्ड डिज़ाइन", - "step-solution-installation": "समाधान इंस्टॉलेशन", "step-reading-device-data": "डिवाइस डेटा पढ़ा जा रहा है…", "step-analyzing-telemetry-attributes": "टेलीमेट्री और विशेषताओं का विश्लेषण किया जा रहा है…", "step-selecting-widgets": "आपके डेटा के लिए विजेट चुने जा रहे हैं…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "अलार्म नियम बनाए जा रहे हैं…", "step-loading-assembling-dashboards": "डैशबोर्ड तैयार किए जा रहे हैं…", "step-loading-preparing-states": "स्टेट तैयार किए जा रहे हैं…", - "step-loading-initializing-solution": "समाधान आरंभ किया जा रहा है…", - "ai-credits": "AI क्रेडिट", - "ai-credits-update": "प्लान अपग्रेड करें", - "ai-credits-usage": "AI क्रेडिट: {{ max }} में से {{ used }} उपयोग किए गए", - "ai-credits-description": "आपने इस महीने अपने {{ max }} AI क्रेडिट में से {{ used }} का उपयोग किया है। सीमा {{ date }} को रीसेट होगी। अपनी AI क्रेडिट सीमा बढ़ाने के लिए, कृपया अपने सिस्टम एडमिनिस्ट्रेटर से संपर्क करें।" + "step-loading-initializing-solution": "समाधान आरंभ किया जा रहा है…" }, "markdown": { "edit": "संपादित करें", @@ -13821,11 +13767,6 @@ "disk-warning-text": "डिस्क स्पेस कम हो रहा है। डेटा हानि से बचने के लिए डिस्क स्पेस खाली करें या बढ़ाएँ।", "disk-critical-text": "डिस्क स्पेस अत्यधिक कम है। डेटा हानि से बचने के लिए डिस्क स्पेस खाली करें या बढ़ाएँ।" }, - "cluster-info": { - "service-id": "सर्विस ID", - "service-type": "सर्विस प्रकार", - "no-data": "कोई डेटा नहीं" - }, "transport-messages": { "title": "ट्रांसपोर्ट संदेश", "info": "डिवाइसों से आए सभी संदेश" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "अभी तक कोई हाल में देखा गया डैशबोर्ड नहीं" }, "configured-features": { - "title": "कॉन्फ़िगर किए गए फ़ीचर", - "info": "ऐसे फ़ीचरों की स्थिति जिन्हें कॉन्फ़िगरेशन की आवश्यकता है", - "white-labeling-feature": "व्हाइट लेबलिंग", - "email-feature": "ईमेल", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "फ़ीचर कॉन्फ़िगर है।\nसेटअप करने के लिए क्लिक करें", "feature-not-configured": "फ़ीचर कॉन्फ़िगर नहीं है।\nसेटअप करने के लिए क्लिक करें" }, - "version-info": { - "title": "संस्करण", - "contact-us": "हमसे संपर्क करें", - "current-version": "वर्तमान संस्करण", - "current": "वर्तमान", - "available-version": "उपलब्ध संस्करण", - "available": "उपलब्ध", - "upgrade": "अपग्रेड करें", - "version-is-up-to-date": "संस्करण नवीनतम है" - }, - "license-info": { - "title": "लाइसेंस जानकारी", - "view-all": "सभी देखें", - "license-portal": "लाइसेंस पोर्टल", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } डिवाइस", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } एसेट", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } डैशबोर्ड", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } इंटीग्रेशन", - "community-support": "कम्युनिटी सपोर्ट", - "white-labeling": "व्हाइट लेबलिंग", - "unlimited-datapoints-and-messages": "असीमित डेटापॉइंट और संदेश", - "unlimited-api-calls": "असीमित API कॉल" - }, "usage-info": { "title": "उपयोग", "entities": "एंटिटी", diff --git a/ui-ngx/src/assets/locale/locale.constant-it_IT.json b/ui-ngx/src/assets/locale/locale.constant-it_IT.json index 52675dc7eb..40588f4ce1 100644 --- a/ui-ngx/src/assets/locale/locale.constant-it_IT.json +++ b/ui-ngx/src/assets/locale/locale.constant-it_IT.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configura con l'IA", - "follow-up-prompt-placeholder": "Rispondi...", - "sub-title": "Posso aiutarti a configurare e gestire i tuoi dispositivi, le dashboard, i campi calcolati, le regole di allarme e le notifiche: descrivi semplicemente ciò di cui hai bisogno e penserò io al resto.", "new-chat": "Nuova chat", - "no-chats": "Nessuna chat ancora", "today": "Oggi", "yesterday": "Ieri", "last-7-days": "Ultimi 7 giorni", @@ -703,18 +700,12 @@ "delete-chat-title": "Sei sicuro di voler eliminare '{{name}}'?", "delete-chat-text": "Tutti i messaggi della chat andranno persi", "delete-chat-confirm": "Sì, elimina", - "action-approval-required": "Approvazione dell'azione richiesta", "approve": "Approva", - "approve-all": "Approva tutte le azioni successive", "deny": "Nega", - "processing": "Elaborazione in corso...", "approved": "Fatto", - "denied": "Negato", "error": "Non riuscito", "thinking": "Sto pensando...", - "rename-chat-title": "Rinomina questa chat", - "export-chat": "Esporta chat", - "main-title": "Ciao! Sono il tuo assistente IA" + "export-chat": "Esporta chat" }, "alarm": { "alarm": "Allarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Trascina e rilascia il file delle credenziali dell'account" }, "solution-creator": { - "ai-solution-creator": "Creatore di soluzioni IA", "describe-solution-you-want": "Descrivi la soluzione che vuoi creare", - "enter-your-prompt": "Inserisci il tuo prompt", "target": "Destinazione", "install-solution": "Installa", - "solution-overview": "Panoramica della soluzione: {{ name }}", - "dashboards-overview": "Panoramica delle dashboard: {{ name }}", - "entity-profile": "Profilo entità", - "entity-profiles": "Profili entità", - "name": "Nome", - "iam": "IAM", - "iam-full": "Gestione delle identità e degli accessi", - "table-view": "Tabella", - "schema-view": "Schema", - "iam-info": "Info IAM", "operation": { "C": "Crea", "R": "Leggi", "U": "Modifica", "D": "Elimina" }, - "alarm-info": "Informazioni sull'allarme", "description": "Descrizione", - "data": "Dati", - "entity-info": "Informazioni sull'entità", - "calculated-field-info": "Informazioni sul campo calcolato", - "field-type": "Tipo di campo", - "scope": "Ambito", "delete-alarm-title": "Eliminare questo allarme suggerito?", "delete-alarm-text": "Questo allarme, suggerito in base alla tua descrizione, non verrà aggiunto alla soluzione proposta.
    Puoi sempre modificare o ricreare gli allarmi manualmente in seguito. Questa azione non può essere annullata.", - "basic-mode": "Base", - "advanced-mode": "Avanzato", "create-solution": "Crea soluzione", "go-dashboard-manager": "Avanti: progettazione della dashboard", - "success-generate-title": "La soluzione è pronta!", - "success-generate-sub-title": "Puoi installarla sul tuo account facendo clic sul pulsante qui sotto", - "success-generate-install-title": "Soluzione installata!", - "success-generate-install-sub-title": "Per modificare la soluzione, disinstalla prima l'istanza esistente", - "main-title": "Ciao! Sono il tuo assistente IA", - "sub-title": "Ti aiuto a trasformare i tuoi requisiti in una soluzione IoT completamente funzionante.\nDescrivi semplicemente cosa vuoi ottenere e al resto penso io.", - "solutions": "Soluzioni", "new-solution": "Nuova soluzione", "uninstall-solution": "Disinstalla", "uninstall-solution-dialog-title": "Sei sicuro di voler disinstallare ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Tutti i tuoi dati andranno persi", "delete-solution-confirm": "Sì, elimina", "copy-solution": "Copia soluzione", - "expand-sidebar": "Espandi barra laterale", - "collapse-sidebar": "Comprimi barra laterale", "solution-id": "ID soluzione", "solution-id-required": "L'ID soluzione è obbligatorio", - "rename-solution-title": "Rinomina questa soluzione", - "generate-again": "Genera di nuovo", "skip-interview": "Salta intervista", "update-solution": "Aggiorna soluzione", "finish-edit": "Termina modifica", @@ -11298,8 +11258,6 @@ "water-metering": "Misurazione dei consumi idrici", "coffee-machine-monitoring": "Monitoraggio macchine del caffè", "fleet-geofencing": "Geofencing della flotta", - "more-examples": "Altri esempi", - "hide": "Nascondi", "solution-info": "Informazioni sulla soluzione", "solution-info-with-name": "Informazioni sulla soluzione: {{ name }}", "status": "Stato", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Dashboard principale", "view-as": "Visualizza come {{ name }}", - "generated-by-calculated-field-name": "Generato dal campo calcolato ‘{{ name }}’", "estimate-wait-time": "Il tempo di attesa stimato è di ~{{ time }}", - "analyzing-your-request": "Analisi della tua richiesta in corso...", "condition": "Condizione", - "installing": "Installazione della soluzione in corso...", - "step-architecture-design": "Progettazione dell'architettura", - "step-dashboard-design": "Progettazione della dashboard", - "step-solution-installation": "Installazione della soluzione", "step-reading-device-data": "Lettura dei dati del dispositivo…", "step-analyzing-telemetry-attributes": "Analisi di telemetria e attributi…", "step-selecting-widgets": "Selezione dei widget per i tuoi dati…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Creazione delle regole di allarme…", "step-loading-assembling-dashboards": "Assemblaggio delle dashboard…", "step-loading-preparing-states": "Preparazione degli stati…", - "step-loading-initializing-solution": "Inizializzazione della soluzione…", - "ai-credits": "Crediti IA", - "ai-credits-update": "Cambia piano", - "ai-credits-usage": "Crediti IA: {{ used }} di {{ max }} utilizzati", - "ai-credits-description": "Hai utilizzato {{ used }} dei tuoi {{ max }} crediti IA questo mese. Il limite si azzera il {{ date }}. Per aumentare la tua disponibilità di crediti IA, contatta l'amministratore di sistema." + "step-loading-initializing-solution": "Inizializzazione della soluzione…" }, "markdown": { "edit": "Modifica", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Spazio su disco in esaurimento. Per evitare la perdita di dati, libera o amplia lo spazio su disco.", "disk-critical-text": "Spazio su disco criticamente basso. Per evitare la perdita di dati, libera o amplia lo spazio su disco." }, - "cluster-info": { - "service-id": "ID servizio", - "service-type": "Tipo di servizio", - "no-data": "Nessun dato" - }, "transport-messages": { "title": "Messaggi di trasporto", "info": "Tutti i messaggi provenienti dai dispositivi" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Nessuna dashboard visualizzata di recente" }, "configured-features": { - "title": "Funzionalità configurate", - "info": "Stato delle funzionalità che richiedono configurazione", - "white-labeling-feature": "Personalizzazione del marchio", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funzionalità configurata.\nClicca per configurare", "feature-not-configured": "Funzionalità non configurata.\nClicca per configurare" }, - "version-info": { - "title": "Versione", - "contact-us": "Contattaci", - "current-version": "Versione corrente", - "current": "Corrente", - "available-version": "Versione disponibile", - "available": "Disponibile", - "upgrade": "Effettua l'upgrade", - "version-is-up-to-date": "La versione è aggiornata" - }, - "license-info": { - "title": "Informazioni sulla licenza", - "view-all": "Vedi tutto", - "license-portal": "Portale licenze", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivi", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Asset", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboard", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrazioni", - "community-support": "Supporto della community", - "white-labeling": "Personalizzazione del marchio", - "unlimited-datapoints-and-messages": "Punti dati e messaggi illimitati", - "unlimited-api-calls": "Chiamate API illimitate" - }, "usage-info": { "title": "Utilizzo", "entities": "Entità", diff --git a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json index 2abd46f029..69eff0732e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json +++ b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI で構成", - "follow-up-prompt-placeholder": "返信...", - "sub-title": "デバイス、ダッシュボード、計算フィールド、アラームルール、通知の設定と管理をお手伝いします。必要なことを説明していただければ、あとはお任せください。", "new-chat": "新しいチャット", - "no-chats": "チャットはまだありません", "today": "今日", "yesterday": "昨日", "last-7-days": "過去 7 日", @@ -703,18 +700,12 @@ "delete-chat-title": "'{{name}}' を削除してもよろしいですか?", "delete-chat-text": "すべてのチャットメッセージが失われます", "delete-chat-confirm": "はい、削除します", - "action-approval-required": "操作の承認が必要です", "approve": "承認", - "approve-all": "以降のすべてのアクションを承認", "deny": "拒否", - "processing": "処理中...", "approved": "完了", - "denied": "拒否済み", "error": "失敗", "thinking": "考え中...", - "rename-chat-title": "このチャットの名前を変更", - "export-chat": "チャットをエクスポート", - "main-title": "こんにちは!AI アシスタントです" + "export-chat": "チャットをエクスポート" }, "alarm": { "alarm": "アラーム", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "アカウント認証情報ファイルをドラッグ&ドロップ" }, "solution-creator": { - "ai-solution-creator": "AIソリューション作成", "describe-solution-you-want": "作成したいソリューションを説明してください", - "enter-your-prompt": "プロンプトを入力", "target": "ターゲット", "install-solution": "インストール", - "solution-overview": "ソリューションの概要: {{ name }}", - "dashboards-overview": "ダッシュボードの概要: {{ name }}", - "entity-profile": "エンティティプロファイル", - "entity-profiles": "エンティティプロファイル", - "name": "名前", - "iam": "IAM", - "iam-full": "IDおよびアクセス管理", - "table-view": "テーブル", - "schema-view": "スキーマ", - "iam-info": "IAM情報", "operation": { "C": "作成", "R": "読み取り", "U": "更新", "D": "削除" }, - "alarm-info": "アラーム情報", "description": "説明", - "data": "データ", - "entity-info": "エンティティ情報", - "calculated-field-info": "計算フィールド情報", - "field-type": "フィールドタイプ", - "scope": "スコープ", "delete-alarm-title": "この提案されたアラームを削除しますか?", "delete-alarm-text": "説明に基づいて提案されたこのアラームは、提案されたソリューションのビルドに追加されません。
    アラームは後からいつでも手動で編集または再作成できます。この操作は元に戻せません。", - "basic-mode": "基本", - "advanced-mode": "詳細", "create-solution": "ソリューションを作成", "go-dashboard-manager": "次へ: ダッシュボード設計", - "success-generate-title": "ソリューションの準備ができました!", - "success-generate-sub-title": "下のボタンをクリックすると、お使いのアカウントにインストールできます。", - "success-generate-install-title": "ソリューションがインストールされました!", - "success-generate-install-sub-title": "ソリューションを編集するには、まず既存のインスタンスをアンインストールしてください。", - "main-title": "こんにちは!AIアシスタントです", - "sub-title": "要件を完全に機能するIoTソリューションに変換するお手伝いをします。\n実現したいことを説明していただければ、残りは私が対応します。", - "solutions": "ソリューション", "new-solution": "新しいソリューション", "uninstall-solution": "アンインストール", "uninstall-solution-dialog-title": "‘{{ name }}’をアンインストールしてもよろしいですか?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "すべてのデータが失われます", "delete-solution-confirm": "はい、削除します", "copy-solution": "ソリューションをコピー", - "expand-sidebar": "サイドバーを展開", - "collapse-sidebar": "サイドバーを折りたたむ", "solution-id": "ソリューションID", "solution-id-required": "ソリューションIDは必須です。", - "rename-solution-title": "このソリューションの名前を変更", - "generate-again": "再生成", "skip-interview": "インタビューをスキップ", "update-solution": "ソリューションを更新", "finish-edit": "編集を終了", @@ -11298,8 +11258,6 @@ "water-metering": "水道検針", "coffee-machine-monitoring": "コーヒーマシンのモニタリング", "fleet-geofencing": "車両ジオフェンシング", - "more-examples": "その他の例", - "hide": "非表示", "solution-info": "ソリューション情報", "solution-info-with-name": "ソリューション情報: {{ name }}", "status": "ステータス", @@ -11312,14 +11270,8 @@ "info": "情報", "main-dashboard": "メインダッシュボード", "view-as": "{{ name }}として表示", - "generated-by-calculated-field-name": "計算フィールド‘{{ name }}’によって生成", "estimate-wait-time": "推定待ち時間は約{{ time }}です。", - "analyzing-your-request": "リクエストを分析しています...", "condition": "条件", - "installing": "ソリューションをインストールしています...", - "step-architecture-design": "アーキテクチャ設計", - "step-dashboard-design": "ダッシュボード設計", - "step-solution-installation": "ソリューションのインストール", "step-reading-device-data": "デバイスデータを読み取っています…", "step-analyzing-telemetry-attributes": "テレメトリと属性を分析しています…", "step-selecting-widgets": "データに適したウィジェットを選択しています…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "アラームルールを構築しています…", "step-loading-assembling-dashboards": "ダッシュボードを構成しています…", "step-loading-preparing-states": "状態を準備しています…", - "step-loading-initializing-solution": "ソリューションを初期化しています…", - "ai-credits": "AIクレジット", - "ai-credits-update": "プランを変更", - "ai-credits-usage": "AIクレジット: {{ used }}/{{ max }}使用済み", - "ai-credits-description": "今月はAIクレジット{{ max }}のうち{{ used }}を使用しました。上限は{{ date }}にリセットされます。AIクレジットの上限を増やすには、システム管理者にお問い合わせください。" + "step-loading-initializing-solution": "ソリューションを初期化しています…" }, "markdown": { "edit": "編集", @@ -13781,11 +13729,6 @@ "disk-warning-text": "ディスクの空き容量が少なくなっています。データ損失を避けるため、ディスクの空き容量を確保するか、ディスクの容量を増加させてください。", "disk-critical-text": "ディスクの空き容量が非常に少ない状態です。データ損失を避けるため、ディスクの空き容量を確保するか、ディスクの容量を増加させてください。" }, - "cluster-info": { - "service-id": "サービスID", - "service-type": "サービスタイプ", - "no-data": "データなし" - }, "transport-messages": { "title": "トランスポートメッセージ", "info": "デバイスから送信されたすべてのメッセージ" @@ -13824,41 +13767,9 @@ "no-last-viewed-dashboards": "最後に表示したダッシュボードはまだありません" }, "configured-features": { - "title": "設定された機能", - "info": "設定が必要な機能の状態", - "white-labeling-feature": "ホワイトラベリング", - "email-feature": "メール", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "機能は設定されています。\n設定するにはクリック", "feature-not-configured": "機能は設定されていません。\n設定するにはクリック" }, - "version-info": { - "title": "バージョン", - "contact-us": "お問い合わせ", - "current-version": "現在のバージョン", - "current": "現行", - "available-version": "利用可能なバージョン", - "available": "利用可能", - "upgrade": "アップグレード", - "version-is-up-to-date": "バージョンは最新です" - }, - "license-info": { - "title": "ライセンス情報", - "view-all": "すべて表示", - "license-portal": "ライセンスポータル", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } デバイス", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } アセット", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } ダッシュボード", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } 統合", - "community-support": "コミュニティサポート", - "white-labeling": "ホワイトラベリング", - "unlimited-datapoints-and-messages": "無制限のデータポイントとメッセージ", - "unlimited-api-calls": "無制限のAPI呼び出し" - }, "usage-info": { "title": "使用状況", "entities": "エンティティ", diff --git a/ui-ngx/src/assets/locale/locale.constant-ka_GE.json b/ui-ngx/src/assets/locale/locale.constant-ka_GE.json index f5f661cd8e..cc6050177d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ka_GE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ka_GE.json @@ -132,10 +132,7 @@ }, "ai-assistant": { "configure-with-ai": "კონფიგურაცია AI-ის დახმარებით", - "follow-up-prompt-placeholder": "პასუხი...", - "sub-title": "შემიძლია დაგეხმაროთ თქვენი მოწყობილობების, დაფების, გამოთვლილი ველების, განგაშის წესებისა და შეტყობინებების დაყენებასა და მართვაში — უბრალოდ აღწერეთ, რა გჭირდებათ, დანარჩენს მე მოვაგვარებ.", "new-chat": "ახალი ჩატი", - "no-chats": "ჩატები ჯერ არ არის", "today": "დღეს", "yesterday": "გუშინ", "last-7-days": "ბოლო 7 დღე", @@ -143,16 +140,11 @@ "delete-chat-title": "ნამდვილად გსურთ '{{name}}'-ის წაშლა?", "delete-chat-text": "ჩატის ყველა შეტყობინება დაიკარგება", "delete-chat-confirm": "კი, წაშლა", - "action-approval-required": "საჭიროა მოქმედების დამტკიცება", "approve": "დამტკიცება", "deny": "უარყოფა", - "processing": "მიმდინარეობს დამუშავება...", "approved": "შესრულებულია", - "denied": "უარყოფილია", "error": "ვერ მოხერხდა", - "thinking": "ვფიქრობ...", - "rename-chat-title": "ამ ჩატის სახელის შეცვლა", - "main-title": "გამარჯობა! მე ვარ თქვენი AI ასისტენტი" + "thinking": "ვფიქრობ..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "განგაშის წესების შეთავაზება", diff --git a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json index eb466cf98a..aa0ebe127b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ko_KR.json +++ b/ui-ngx/src/assets/locale/locale.constant-ko_KR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "AI로 구성", - "follow-up-prompt-placeholder": "답장...", - "sub-title": "장치, 대시보드, 계산 필드, 알람 규칙, 알림을 설정하고 관리하는 것을 도와드릴 수 있습니다. 필요한 것을 설명해 주시면 나머지는 제가 처리하겠습니다.", "new-chat": "새 채팅", - "no-chats": "아직 채팅이 없습니다", "today": "오늘", "yesterday": "어제", "last-7-days": "지난 7일", @@ -703,17 +700,11 @@ "delete-chat-title": "'{{name}}'을(를) 삭제하시겠습니까?", "delete-chat-text": "모든 채팅 메시지가 손실됩니다", "delete-chat-confirm": "예, 삭제", - "action-approval-required": "액션 승인이 필요합니다", "approve": "승인", - "approve-all": "이후 모든 액션 승인", "deny": "거부", - "processing": "처리 중...", "approved": "완료", - "denied": "거부됨", "error": "실패", "thinking": "생각 중...", - "connection-lost": "AI 어시스턴트와의 연결이 끊어졌습니다. 다시 연결하는 중...", - "reconnect-failed": "AI 어시스턴트에 다시 연결할 수 없습니다. 응답을 보려면 채팅을 다시 여세요.", "ask-the-assistant": "AI 어시스턴트에게 질문", "send": "보내기", "new-line": "줄 바꿈", @@ -740,9 +731,7 @@ "text": "텍스트", "file": "파일" }, - "rename-chat-title": "이 채팅 이름 바꾸기", - "export-chat": "채팅 내보내기", - "main-title": "안녕하세요! AI 어시스턴트입니다" + "export-chat": "채팅 내보내기" }, "alarm-rule": { "ai-assistant-initial-prompt-placeholder": "설정하려는 내용을 설명해 주세요...", @@ -11347,47 +11336,20 @@ "select-recaptcha-enterprise-service-account-file": "계정 자격 증명 파일을 끌어서 놓으세요" }, "solution-creator": { - "ai-solution-creator": "AI 솔루션 생성기", "describe-solution-you-want": "만들려는 솔루션을 설명하세요", - "enter-your-prompt": "프롬프트를 입력하세요", "target": "대상", "install-solution": "설치", - "solution-overview": "솔루션 개요: {{ name }}", - "dashboards-overview": "대시보드 개요: {{ name }}", - "entity-profile": "엔티티 프로필", - "entity-profiles": "엔티티 프로필", - "name": "이름", - "iam": "IAM", - "iam-full": "ID 및 액세스 관리", - "table-view": "테이블", - "schema-view": "스키마", - "iam-info": "IAM 정보", "operation": { "C": "생성", "R": "읽기", "U": "업데이트", "D": "삭제" }, - "alarm-info": "알람 정보", "description": "설명", - "data": "데이터", - "entity-info": "엔티티 정보", - "calculated-field-info": "계산 필드 정보", - "field-type": "필드 유형", - "scope": "범위", "delete-alarm-title": "제안된 이 알람을 삭제하시겠습니까?", "delete-alarm-text": "입력하신 설명을 바탕으로 제안된 이 알람은 제안된 솔루션 빌드에 추가되지 않습니다.
    나중에 언제든지 알람을 수동으로 편집하거나 다시 생성할 수 있습니다. 이 작업은 실행 취소할 수 없습니다.", - "basic-mode": "기본", - "advanced-mode": "고급", "create-solution": "솔루션 생성", "go-dashboard-manager": "다음: 대시보드 디자인", - "success-generate-title": "솔루션이 준비되었습니다!", - "success-generate-sub-title": "아래 버튼을 클릭하여 계정에 설치할 수 있습니다", - "success-generate-install-title": "솔루션이 설치되었습니다!", - "success-generate-install-sub-title": "솔루션을 편집하려면 먼저 기존 인스턴스를 제거하세요", - "main-title": "안녕하세요! AI 어시스턴트입니다", - "sub-title": "요구 사항을 완전히 작동하는 IoT 솔루션으로 구현하도록 도와드립니다.\n원하는 목표를 설명해 주시면 나머지는 제가 처리하겠습니다.", - "solutions": "솔루션", "new-solution": "새 솔루션", "uninstall-solution": "제거", "uninstall-solution-dialog-title": "‘{{ name }}’을(를) 제거하시겠습니까?", @@ -11397,12 +11359,8 @@ "delete-solution-text": "모든 데이터가 손실됩니다", "delete-solution-confirm": "예, 삭제", "copy-solution": "솔루션 복사", - "expand-sidebar": "사이드바 확장", - "collapse-sidebar": "사이드바 축소", "solution-id": "솔루션 ID", "solution-id-required": "솔루션 ID는 필수 항목입니다.", - "rename-solution-title": "이 솔루션 이름 변경", - "generate-again": "다시 생성", "skip-interview": "인터뷰 생략", "update-solution": "솔루션 업데이트", "finish-edit": "편집 완료", @@ -11412,8 +11370,6 @@ "water-metering": "수도 계량", "coffee-machine-monitoring": "커피 머신 모니터링", "fleet-geofencing": "차량 지오펜싱", - "more-examples": "더 많은 예시", - "hide": "숨기기", "solution-info": "솔루션 정보", "solution-info-with-name": "솔루션 정보: {{ name }}", "status": "상태", @@ -11426,14 +11382,8 @@ "info": "정보", "main-dashboard": "메인 대시보드", "view-as": "{{ name }}(으)로 보기", - "generated-by-calculated-field-name": "‘{{ name }}’ 계산 필드에서 생성됨", "estimate-wait-time": "예상 대기 시간은 약 {{ time }}입니다", - "analyzing-your-request": "요청을 분석하는 중...", "condition": "조건", - "installing": "솔루션 설치 중...", - "step-architecture-design": "아키텍처 설계", - "step-dashboard-design": "대시보드 디자인", - "step-solution-installation": "솔루션 설치", "step-reading-device-data": "장치 데이터 읽는 중…", "step-analyzing-telemetry-attributes": "텔레메트리 및 속성 분석 중…", "step-selecting-widgets": "데이터에 맞는 위젯 선택 중…", @@ -11465,11 +11415,7 @@ "step-loading-building-alarm-rules": "알람 규칙 생성 중…", "step-loading-assembling-dashboards": "대시보드 조립 중…", "step-loading-preparing-states": "상태 준비 중…", - "step-loading-initializing-solution": "솔루션 초기화 중…", - "ai-credits": "AI 크레딧", - "ai-credits-update": "플랜 변경", - "ai-credits-usage": "AI 크레딧: {{ max }}개 중 {{ used }}개 사용", - "ai-credits-description": "이번 달 AI 크레딧 {{ max }}개 중 {{ used }}개를 사용했습니다. 한도는 {{ date }}에 재설정됩니다. AI 크레딧 한도를 늘리려면 시스템 관리자에게 문의하세요." + "step-loading-initializing-solution": "솔루션 초기화 중…" }, "widgets": { "mobile-app-qr-code": { @@ -13813,11 +13759,6 @@ "disk-warning-text": "디스크 공간이 부족합니다. 데이터 손실을 방지하려면 디스크 공간을 확보하거나 늘리세요.", "disk-critical-text": "디스크 공간이 매우 부족합니다. 데이터 손실을 방지하려면 디스크 공간을 확보하거나 늘리세요." }, - "cluster-info": { - "service-id": "서비스 ID", - "service-type": "서비스 유형", - "no-data": "데이터 없음" - }, "transport-messages": { "title": "전송 메시지", "info": "장치에서 온 모든 메시지" @@ -13856,41 +13797,9 @@ "no-last-viewed-dashboards": "아직 최근 본 대시보드 없음" }, "configured-features": { - "title": "구성된 기능", - "info": "구성이 필요한 기능 상태", - "white-labeling-feature": "화이트 라벨링", - "email-feature": "이메일", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2단계 인증", "feature-configured": "기능이 구성되었습니다.\n클릭하여 설정", "feature-not-configured": "기능이 구성되지 않았습니다.\n클릭하여 설정" }, - "version-info": { - "title": "버전", - "contact-us": "문의하기", - "current-version": "현재 버전", - "current": "현재", - "available-version": "사용 가능한 버전", - "available": "사용 가능", - "upgrade": "업그레이드", - "version-is-up-to-date": "버전이 최신 상태입니다" - }, - "license-info": { - "title": "라이선스 정보", - "view-all": "모두 보기", - "license-portal": "라이선스 포털", - "devices-info": "장치 {count} / { max, plural, =0 {∞} other {#} }", - "assets-info": "자산 {count} / { max, plural, =0 {∞} other {#} }", - "edges-info": "Edge {count} / { max, plural, =0 {∞} other {#} }", - "dashboards-info": "대시보드 {count} / { max, plural, =0 {∞} other {#} }", - "integrations-info": "통합 {count} / { max, plural, =0 {∞} other {#} }", - "community-support": "커뮤니티 지원", - "white-labeling": "화이트 라벨링", - "unlimited-datapoints-and-messages": "무제한 데이터 포인트 및 메시지", - "unlimited-api-calls": "무제한 API 호출" - }, "usage-info": { "title": "사용량", "entities": "엔티티", diff --git a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json index 9268a71e6a..179bfb4476 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json +++ b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigūruoti naudojant DI", - "follow-up-prompt-placeholder": "Atsakykite...", - "sub-title": "Galiu padėti jums nustatyti ir valdyti jūsų įrenginius, skydelius, apskaičiuotus laukus, įspėjimų taisykles ir pranešimus — tiesiog apibūdinkite, ko jums reikia, o likusiais pasirūpinsiu aš.", "new-chat": "Naujas pokalbis", - "no-chats": "Pokalbių dar nėra", "today": "Šiandien", "yesterday": "Vakar", "last-7-days": "Paskutinės 7 dienos", @@ -703,17 +700,11 @@ "delete-chat-title": "Ar tikrai norite ištrinti „{{name}}“?", "delete-chat-text": "Visi pokalbio pranešimai bus prarasti", "delete-chat-confirm": "Taip, ištrinti", - "action-approval-required": "Reikalingas veiksmo patvirtinimas", "approve": "Patvirtinti", - "approve-all": "Patvirtinti visus tolesnius veiksmus", "deny": "Atmesti", - "processing": "Apdorojama...", "approved": "Atlikta", - "denied": "Atmesta", "error": "Nepavyko", "thinking": "Galvoju...", - "connection-lost": "Ryšys su DI asistentu nutrūko. Jungiamasi iš naujo...", - "reconnect-failed": "Nepavyko iš naujo prisijungti prie DI asistento. Atidarykite pokalbį iš naujo, kad pamatytumėte jo atsakymą.", "ask-the-assistant": "Paklausti DI asistento", "send": "Siųsti", "new-line": "Nauja eilutė", @@ -740,9 +731,7 @@ "text": "Tekstas", "file": "Failas" }, - "rename-chat-title": "Pervadinti šį pokalbį", - "export-chat": "Eksportuoti pokalbį", - "main-title": "Sveiki! Aš esu jūsų DI asistentas" + "export-chat": "Eksportuoti pokalbį" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Siūlyti įspėjimų taisykles", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "Nuvilkite savo paskyros prisijungimo duomenų failą" }, "solution-creator": { - "ai-solution-creator": "DI sprendimų kūrėjas", "describe-solution-you-want": "Aprašykite sprendimą, kurį norite sukurti", - "enter-your-prompt": "Įveskite užklausą", "target": "Tikslas", "install-solution": "Įdiegti", - "solution-overview": "Sprendimo apžvalga: {{ name }}", - "dashboards-overview": "Skydelių apžvalga: {{ name }}", - "entity-profile": "Subjekto profilis", - "entity-profiles": "Subjektų profiliai", - "name": "Pavadinimas", - "iam": "IAM", - "iam-full": "Tapatybių ir prieigos valdymas", - "table-view": "Lentelė", - "schema-view": "Schema", - "iam-info": "IAM informacija", "operation": { "C": "Sukurti", "R": "Skaityti", "U": "Keisti", "D": "Ištrinti" }, - "alarm-info": "Įspėjimo informacija", "description": "Aprašymas", - "data": "Duomenys", - "entity-info": "Subjekto informacija", - "calculated-field-info": "Apskaičiuoto lauko informacija", - "field-type": "Lauko tipas", - "scope": "Taikymo sritis", "delete-alarm-title": "Ištrinti šį pasiūlytą įspėjimą?", "delete-alarm-text": "Šis pagal jūsų aprašymą pasiūlytas įspėjimas nebus įtrauktas į siūlomo sprendimo rinkinį.
    Vėliau visada galėsite įspėjimus redaguoti arba sukurti iš naujo rankiniu būdu. Šio veiksmo anuliuoti negalima.", - "basic-mode": "Paprastas režimas", - "advanced-mode": "Išplėstinis režimas", "create-solution": "Sukurti sprendimą", "go-dashboard-manager": "Toliau: skydelio dizainas", - "success-generate-title": "Sprendimas paruoštas!", - "success-generate-sub-title": "Galite jį įdiegti savo paskyroje spustelėję toliau esantį mygtuką", - "success-generate-install-title": "Sprendimas įdiegtas!", - "success-generate-install-sub-title": "Norėdami redaguoti sprendimą, pirmiausia išdiekite esamą egzempliorių", - "main-title": "Sveiki! Aš esu jūsų DI asistentas", - "sub-title": "Padedu jūsų reikalavimus paversti visiškai veikiančiu IoT sprendimu.\nTiesiog aprašykite, ko norite pasiekti, o visa kita padarysiu aš.", - "solutions": "Sprendimai", "new-solution": "Naujas sprendimas", "uninstall-solution": "Išdiegti", "uninstall-solution-dialog-title": "Ar tikrai norite išdiegti „{{ name }}“?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "Visi jūsų duomenys bus prarasti", "delete-solution-confirm": "Taip, ištrinti", "copy-solution": "Kopijuoti sprendimą", - "expand-sidebar": "Išskleisti šoninę juostą", - "collapse-sidebar": "Suskleisti šoninę juostą", "solution-id": "Sprendimo ID", "solution-id-required": "Sprendimo ID yra privalomas", - "rename-solution-title": "Pervadinti šį sprendimą", - "generate-again": "Generuoti dar kartą", "skip-interview": "Praleisti interviu", "update-solution": "Atnaujinti sprendimą", "finish-edit": "Baigti redaguoti", @@ -11338,8 +11296,6 @@ "water-metering": "Vandens apskaita", "coffee-machine-monitoring": "Kavos aparatų stebėsena", "fleet-geofencing": "Transporto parko geozonos", - "more-examples": "Daugiau pavyzdžių", - "hide": "Slėpti", "solution-info": "Sprendimo informacija", "solution-info-with-name": "Sprendimo informacija: {{ name }}", "status": "Būsena", @@ -11352,14 +11308,8 @@ "info": "Informacija", "main-dashboard": "Pagrindinis skydelis", "view-as": "Peržiūrėti kaip {{ name }}", - "generated-by-calculated-field-name": "Sugeneruota apskaičiuoto lauko „{{ name }}“", "estimate-wait-time": "Numatomas laukimo laikas – ~{{ time }}", - "analyzing-your-request": "Analizuojama jūsų užklausa...", "condition": "Sąlyga", - "installing": "Diegiamas sprendimas...", - "step-architecture-design": "Architektūros projektavimas", - "step-dashboard-design": "Skydelio projektavimas", - "step-solution-installation": "Sprendimo diegimas", "step-reading-device-data": "Skaitomi įrenginio duomenys…", "step-analyzing-telemetry-attributes": "Analizuojama telemetrija ir atributai…", "step-selecting-widgets": "Parenkami valdikliai jūsų duomenims…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "Kuriamos įspėjimų taisyklės…", "step-loading-assembling-dashboards": "Komponuojami skydeliai…", "step-loading-preparing-states": "Ruošiamos būsenos…", - "step-loading-initializing-solution": "Inicijuojamas sprendimas…", - "ai-credits": "DI kreditai", - "ai-credits-update": "Keisti planą", - "ai-credits-usage": "DI kreditai: panaudota {{ used }} iš {{ max }}", - "ai-credits-description": "Šį mėnesį panaudojote {{ used }} iš savo {{ max }} DI kreditų. Limitas atsinaujins {{ date }}. Norėdami padidinti DI kreditų limitą, susisiekite su sistemos administratoriumi." + "step-loading-initializing-solution": "Inicijuojamas sprendimas…" }, "markdown": { "edit": "Redaguoti", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Baigiasi vieta diske. Kad neprarastumėte duomenų, atlaisvinkite arba išplėskite disko vietą.", "disk-critical-text": "Kritiškai mažai vietos diske. Kad neprarastumėte duomenų, atlaisvinkite arba išplėskite disko vietą." }, - "cluster-info": { - "service-id": "Paslaugos ID", - "service-type": "Paslaugos tipas", - "no-data": "Nėra duomenų" - }, "transport-messages": { "title": "Transporto žinutės", "info": "Visos žinutės, gautos iš įrenginių" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Dar nėra peržiūrėtų skydelių" }, "configured-features": { - "title": "Sukonfigūruotos funkcijos", - "info": "Funkcijų, kurioms reikia konfigūracijos, būsena", - "white-labeling-feature": "Prekės ženklo tinkinimas", - "email-feature": "El. paštas", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funkcija sukonfigūruota.\nSpustelėkite, kad nustatytumėte", "feature-not-configured": "Funkcija nesukonfigūruota.\nSpustelėkite, kad nustatytumėte" }, - "version-info": { - "title": "Versija", - "contact-us": "Susisiekite su mumis", - "current-version": "Dabartinė versija", - "current": "Dabartinė", - "available-version": "Prieinama versija", - "available": "Prieinama", - "upgrade": "Naujinti", - "version-is-up-to-date": "Versija yra naujausia" - }, - "license-info": { - "title": "Licencijos informacija", - "view-all": "Peržiūrėti visas", - "license-portal": "Licencijų portalas", - "devices-info": "{count} / { max, plural, =0 {∞ įrenginių} one {# įrenginys} few {# įrenginiai} other {# įrenginių} }", - "assets-info": "{count} / { max, plural, =0 {∞ turtų} one {# turtas} few {# turtai} other {# turtų} }", - "edges-info": "{count} / { max, plural, =0 {∞ Edge egzempliorių} one {# Edge egzempliorius} few {# Edge egzemplioriai} other {# Edge egzempliorių} }", - "dashboards-info": "{count} / { max, plural, =0 {∞ skydelių} one {# skydelis} few {# skydeliai} other {# skydelių} }", - "integrations-info": "{count} / { max, plural, =0 {∞ integracijų} one {# integracija} few {# integracijos} other {# integracijų} }", - "community-support": "Bendruomenės palaikymas", - "white-labeling": "Prekės ženklo tinkinimas", - "unlimited-datapoints-and-messages": "Neriboti duomenų taškai ir žinutės", - "unlimited-api-calls": "Neribotos API užklausos" - }, "usage-info": { "title": "Naudojimas", "entities": "Subjektai", diff --git a/ui-ngx/src/assets/locale/locale.constant-lv_LV.json b/ui-ngx/src/assets/locale/locale.constant-lv_LV.json index 36b3e0c6b1..41355162ef 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lv_LV.json +++ b/ui-ngx/src/assets/locale/locale.constant-lv_LV.json @@ -109,10 +109,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurēt ar MI", - "follow-up-prompt-placeholder": "Atbildēt...", - "sub-title": "Es varu palīdzēt jums iestatīt un pārvaldīt jūsu iekārtas, informācijas paneļus, aprēķinātos laukus, trauksmes noteikumus un paziņojumus — vienkārši aprakstiet, kas jums nepieciešams, un par pārējo parūpēšos es.", "new-chat": "Jauna saruna", - "no-chats": "Vēl nav sarunu", "today": "Šodien", "yesterday": "Vakardien", "last-7-days": "Pēdējās 7 dienas", @@ -120,16 +117,11 @@ "delete-chat-title": "Vai tiešām vēlaties dzēst '{{name}}'?", "delete-chat-text": "Visi sarunas ziņojumi tiks zaudēti", "delete-chat-confirm": "Jā, dzēst", - "action-approval-required": "Nepieciešams darbības apstiprinājums", "approve": "Apstiprināt", "deny": "Noraidīt", - "processing": "Apstrādā...", "approved": "Pabeigts", - "denied": "Noraidīts", "error": "Neizdevās", - "thinking": "Domāju...", - "rename-chat-title": "Pārdēvēt šo sarunu", - "main-title": "Sveiki! Es esmu jūsu MI asistents" + "thinking": "Domāju..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Ieteikt trauksmes noteikumus", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json index 3d5a4b2b22..8c3419bb4a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_BE.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_BE.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configureren met AI", - "follow-up-prompt-placeholder": "Antwoord...", - "sub-title": "Ik kan je helpen bij het instellen en beheren van je apparaten, dashboards, berekende velden, alarmregels en meldingen — beschrijf gewoon wat je nodig hebt en ik regel de rest.", "new-chat": "Nieuwe chat", - "no-chats": "Nog geen chats", "today": "Vandaag", "yesterday": "Gisteren", "last-7-days": "Afgelopen 7 dagen", @@ -703,17 +700,11 @@ "delete-chat-title": "Weet je zeker dat je '{{name}}' wilt verwijderen?", "delete-chat-text": "Alle chatberichten gaan verloren", "delete-chat-confirm": "Ja, verwijderen", - "action-approval-required": "Goedkeuring voor actie vereist", "approve": "Goedkeuren", - "approve-all": "Alle verdere acties goedkeuren", "deny": "Weigeren", - "processing": "Bezig met verwerken...", "approved": "Gereed", - "denied": "Geweigerd", "error": "Mislukt", "thinking": "Aan het nadenken...", - "connection-lost": "De verbinding met de AI-assistent is verbroken. Opnieuw verbinden...", - "reconnect-failed": "Kan niet opnieuw verbinden met de AI-assistent. Open de chat opnieuw om het antwoord te zien.", "ask-the-assistant": "Vraag het de AI-assistent", "send": "Verzenden", "new-line": "Nieuwe regel", @@ -740,9 +731,7 @@ "text": "Tekst", "file": "Bestand" }, - "rename-chat-title": "Deze chat hernoemen", - "export-chat": "Chat exporteren", - "main-title": "Hallo! Ik ben je AI-assistent" + "export-chat": "Chat exporteren" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Alarmregels voorstellen", @@ -11279,47 +11268,20 @@ "select-recaptcha-enterprise-service-account-file": "Sleep je accountreferentiesbestand hierheen" }, "solution-creator": { - "ai-solution-creator": "AI-oplossingsmaker", "describe-solution-you-want": "Beschrijf de oplossing die je wilt maken", - "enter-your-prompt": "Voer je prompt in", "target": "Doel", "install-solution": "Installeren", - "solution-overview": "Overzicht van oplossing: {{ name }}", - "dashboards-overview": "Overzicht van dashboards: {{ name }}", - "entity-profile": "Entiteitsprofiel", - "entity-profiles": "Entiteitsprofielen", - "name": "Naam", - "iam": "IAM", - "iam-full": "Identiteits- en toegangsbeheer", - "table-view": "Tabel", - "schema-view": "Schema", - "iam-info": "IAM-info", "operation": { "C": "Aanmaken", "R": "Lezen", "U": "Bijwerken", "D": "Verwijderen" }, - "alarm-info": "Alarminformatie", "description": "Beschrijving", - "data": "Gegevens", - "entity-info": "Entiteitsinformatie", - "calculated-field-info": "Informatie over berekend veld", - "field-type": "Veldtype", - "scope": "Bereik", "delete-alarm-title": "Dit voorgestelde alarm verwijderen?", "delete-alarm-text": "Dit alarm, voorgesteld op basis van je beschrijving, wordt niet toegevoegd aan de voorgestelde build van de oplossing.
    Je kunt alarmen later altijd handmatig bewerken of opnieuw aanmaken. Deze actie kan niet ongedaan worden gemaakt.", - "basic-mode": "Basis", - "advanced-mode": "Geavanceerd", "create-solution": "Oplossing maken", "go-dashboard-manager": "Volgende: dashboardontwerp", - "success-generate-title": "De oplossing is klaar!", - "success-generate-sub-title": "Je kunt deze in je account installeren door op de knop hieronder te klikken", - "success-generate-install-title": "Oplossing geïnstalleerd!", - "success-generate-install-sub-title": "De-installeer eerst de bestaande instantie om de oplossing te bewerken", - "main-title": "Hallo! Ik ben je AI-assistent", - "sub-title": "Ik help je je eisen om te zetten in een volledig functionele IoT-oplossing.\nBeschrijf gewoon wat je wilt bereiken, en ik doe de rest.", - "solutions": "Oplossingen", "new-solution": "Nieuwe oplossing", "uninstall-solution": "De-installeren", "uninstall-solution-dialog-title": "Weet je zeker dat je ‘{{ name }}’ wilt de-installeren?", @@ -11329,12 +11291,8 @@ "delete-solution-text": "Al je gegevens gaan verloren", "delete-solution-confirm": "Ja, verwijderen", "copy-solution": "Oplossing kopiëren", - "expand-sidebar": "Zijbalk uitvouwen", - "collapse-sidebar": "Zijbalk samenvouwen", "solution-id": "Oplossings-ID", "solution-id-required": "Oplossings-ID is verplicht", - "rename-solution-title": "Naam van deze oplossing wijzigen", - "generate-again": "Opnieuw genereren", "skip-interview": "Interview overslaan", "update-solution": "Oplossing bijwerken", "finish-edit": "Bewerken voltooien", @@ -11344,8 +11302,6 @@ "water-metering": "Watermeting", "coffee-machine-monitoring": "Koffiemachinemonitoring", "fleet-geofencing": "Geofencing voor wagenpark", - "more-examples": "Meer voorbeelden", - "hide": "Verbergen", "solution-info": "Oplossingsinfo", "solution-info-with-name": "Oplossingsinfo: {{ name }}", "status": "Status", @@ -11358,14 +11314,8 @@ "info": "Info", "main-dashboard": "Hoofddashboard", "view-as": "Bekijken als {{ name }}", - "generated-by-calculated-field-name": "Gegenereerd door berekend veld ‘{{ name }}’", "estimate-wait-time": "Geschatte wachttijd is ~{{ time }}", - "analyzing-your-request": "Je verzoek wordt geanalyseerd...", "condition": "Voorwaarde", - "installing": "Oplossing wordt geïnstalleerd...", - "step-architecture-design": "Architectuurontwerp", - "step-dashboard-design": "Dashboardontwerp", - "step-solution-installation": "Installatie van oplossing", "step-reading-device-data": "Apparaatgegevens worden gelezen…", "step-analyzing-telemetry-attributes": "Telemetrie & attributen worden geanalyseerd…", "step-selecting-widgets": "Widgets voor je gegevens worden geselecteerd…", @@ -11397,11 +11347,7 @@ "step-loading-building-alarm-rules": "Alarmregels opbouwen…", "step-loading-assembling-dashboards": "Dashboards samenstellen…", "step-loading-preparing-states": "Toestanden voorbereiden…", - "step-loading-initializing-solution": "Oplossing initialiseren…", - "ai-credits": "AI-credits", - "ai-credits-update": "Abonnement wijzigen", - "ai-credits-usage": "AI-credits: {{ used }} van {{ max }} gebruikt", - "ai-credits-description": "Je hebt deze maand {{ used }} van je {{ max }} AI-credits gebruikt. De limiet wordt gereset op {{ date }}. Neem contact op met je systeembeheerder om je AI-credittegoed te verhogen." + "step-loading-initializing-solution": "Oplossing initialiseren…" }, "white-labeling": { "white-labeling": "White labeling", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Weinig schijfruimte beschikbaar. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen.", "disk-critical-text": "Kritiek weinig schijfruimte. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen." }, - "cluster-info": { - "service-id": "Service-ID", - "service-type": "Servicetype", - "no-data": "Geen gegevens" - }, "transport-messages": { "title": "Transportberichten", "info": "Alle berichten afkomstig van apparaten" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Nog geen laatst bekeken dashboards" }, "configured-features": { - "title": "Geconfigureerde functies", - "info": "Status van functies die configuratie vereisen", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Functie is geconfigureerd.\nKlik om in te stellen", "feature-not-configured": "Functie is niet geconfigureerd.\nKlik om in te stellen" }, - "version-info": { - "title": "Versie", - "contact-us": "Neem contact op", - "current-version": "Huidige versie", - "current": "Huidig", - "available-version": "Beschikbare versie", - "available": "Beschikbaar", - "upgrade": "Upgraden", - "version-is-up-to-date": "Versie is up-to-date" - }, - "license-info": { - "title": "Licentie-informatie", - "view-all": "Bekijk alles", - "license-portal": "Licentieportaal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Apparaten", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraties", - "community-support": "Community-ondersteuning", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Onbeperkte datapunten en berichten", - "unlimited-api-calls": "Onbeperkte API-aanroepen" - }, "usage-info": { "title": "Gebruik", "entities": "Entiteiten", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json index 3228981395..10abd98754 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configureren met AI", - "follow-up-prompt-placeholder": "Antwoord...", - "sub-title": "Ik kan je helpen bij het instellen en beheren van je apparaten, dashboards, berekende velden, alarmregels en meldingen — beschrijf gewoon wat je nodig hebt en ik regel de rest.", "new-chat": "Nieuwe chat", - "no-chats": "Nog geen chats", "today": "Vandaag", "yesterday": "Gisteren", "last-7-days": "Afgelopen 7 dagen", @@ -703,18 +700,12 @@ "delete-chat-title": "Weet je zeker dat je '{{name}}' wilt verwijderen?", "delete-chat-text": "Alle chatberichten gaan verloren", "delete-chat-confirm": "Ja, verwijderen", - "action-approval-required": "Goedkeuring voor actie vereist", "approve": "Goedkeuren", - "approve-all": "Alle verdere acties goedkeuren", "deny": "Weigeren", - "processing": "Bezig met verwerken...", "approved": "Gereed", - "denied": "Geweigerd", "error": "Mislukt", "thinking": "Aan het nadenken...", - "rename-chat-title": "Deze chat hernoemen", - "export-chat": "Chat exporteren", - "main-title": "Hallo! Ik ben je AI-assistent" + "export-chat": "Chat exporteren" }, "alarm": { "alarm": "Alarm", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Sleep je accountreferentiesbestand hierheen" }, "solution-creator": { - "ai-solution-creator": "AI-oplossingsmaker", "describe-solution-you-want": "Beschrijf de oplossing die je wilt maken", - "enter-your-prompt": "Voer je prompt in", "target": "Doel", "install-solution": "Installeren", - "solution-overview": "Overzicht van oplossing: {{ name }}", - "dashboards-overview": "Overzicht van dashboards: {{ name }}", - "entity-profile": "Entiteitsprofiel", - "entity-profiles": "Entiteitsprofielen", - "name": "Naam", - "iam": "IAM", - "iam-full": "Identiteits- en toegangsbeheer", - "table-view": "Tabel", - "schema-view": "Schema", - "iam-info": "IAM-info", "operation": { "C": "Aanmaken", "R": "Lezen", "U": "Bijwerken", "D": "Verwijderen" }, - "alarm-info": "Alarminformatie", "description": "Beschrijving", - "data": "Gegevens", - "entity-info": "Entiteitsinformatie", - "calculated-field-info": "Informatie over berekend veld", - "field-type": "Veldtype", - "scope": "Bereik", "delete-alarm-title": "Dit voorgestelde alarm verwijderen?", "delete-alarm-text": "Dit alarm, voorgesteld op basis van je beschrijving, wordt niet toegevoegd aan de voorgestelde build van de oplossing.
    Je kunt alarmen later altijd handmatig bewerken of opnieuw aanmaken. Deze actie kan niet ongedaan worden gemaakt.", - "basic-mode": "Basis", - "advanced-mode": "Geavanceerd", "create-solution": "Oplossing maken", "go-dashboard-manager": "Volgende: dashboardontwerp", - "success-generate-title": "De oplossing is klaar!", - "success-generate-sub-title": "Je kunt deze in je account installeren door op de knop hieronder te klikken", - "success-generate-install-title": "Oplossing geïnstalleerd!", - "success-generate-install-sub-title": "De-installeer eerst de bestaande instantie om de oplossing te bewerken", - "main-title": "Hallo! Ik ben je AI-assistent", - "sub-title": "Ik help je je eisen om te zetten in een volledig functionele IoT-oplossing.\nBeschrijf gewoon wat je wilt bereiken, en ik doe de rest.", - "solutions": "Oplossingen", "new-solution": "Nieuwe oplossing", "uninstall-solution": "De-installeren", "uninstall-solution-dialog-title": "Weet je zeker dat je ‘{{ name }}’ wilt de-installeren?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Al je gegevens gaan verloren", "delete-solution-confirm": "Ja, verwijderen", "copy-solution": "Oplossing kopiëren", - "expand-sidebar": "Zijbalk uitvouwen", - "collapse-sidebar": "Zijbalk samenvouwen", "solution-id": "Oplossings-ID", "solution-id-required": "Oplossings-ID is verplicht", - "rename-solution-title": "Naam van deze oplossing wijzigen", - "generate-again": "Opnieuw genereren", "skip-interview": "Interview overslaan", "update-solution": "Oplossing bijwerken", "finish-edit": "Bewerken voltooien", @@ -11298,8 +11258,6 @@ "water-metering": "Watermeting", "coffee-machine-monitoring": "Koffiemachinemonitoring", "fleet-geofencing": "Geofencing voor wagenpark", - "more-examples": "Meer voorbeelden", - "hide": "Verbergen", "solution-info": "Oplossingsinfo", "solution-info-with-name": "Oplossingsinfo: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Info", "main-dashboard": "Hoofddashboard", "view-as": "Bekijken als {{ name }}", - "generated-by-calculated-field-name": "Gegenereerd door berekend veld ‘{{ name }}’", "estimate-wait-time": "Geschatte wachttijd is ~{{ time }}", - "analyzing-your-request": "Je verzoek wordt geanalyseerd...", "condition": "Voorwaarde", - "installing": "Oplossing wordt geïnstalleerd...", - "step-architecture-design": "Architectuurontwerp", - "step-dashboard-design": "Dashboardontwerp", - "step-solution-installation": "Installatie van oplossing", "step-reading-device-data": "Apparaatgegevens worden gelezen…", "step-analyzing-telemetry-attributes": "Telemetrie & attributen worden geanalyseerd…", "step-selecting-widgets": "Widgets voor je gegevens worden geselecteerd…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarmregels opbouwen…", "step-loading-assembling-dashboards": "Dashboards samenstellen…", "step-loading-preparing-states": "Toestanden voorbereiden…", - "step-loading-initializing-solution": "Oplossing initialiseren…", - "ai-credits": "AI-credits", - "ai-credits-update": "Abonnement wijzigen", - "ai-credits-usage": "AI-credits: {{ used }} van {{ max }} gebruikt", - "ai-credits-description": "Je hebt deze maand {{ used }} van je {{ max }} AI-credits gebruikt. De limiet wordt gereset op {{ date }}. Neem contact op met je systeembeheerder om je AI-credittegoed te verhogen." + "step-loading-initializing-solution": "Oplossing initialiseren…" }, "markdown": { "edit": "Bewerken", @@ -13781,11 +13729,6 @@ "disk-warning-text": "Weinig schijfruimte beschikbaar. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen.", "disk-critical-text": "Kritieke schijfruimte. Maak ruimte vrij of vergroot de opslagcapaciteit om dataverlies te voorkomen." }, - "cluster-info": { - "service-id": "Service-ID", - "service-type": "Servicetype", - "no-data": "Geen gegevens" - }, "transport-messages": { "title": "Transportberichten", "info": "Alle berichten afkomstig van apparaten" @@ -13824,41 +13767,9 @@ "no-last-viewed-dashboards": "Nog geen laatst bekeken dashboards" }, "configured-features": { - "title": "Geconfigureerde functies", - "info": "Status van functies die configuratie vereisen", - "white-labeling-feature": "White labeling", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Functie is geconfigureerd.\nKlik om in te stellen", "feature-not-configured": "Functie is niet geconfigureerd.\nKlik om in te stellen" }, - "version-info": { - "title": "Versie", - "contact-us": "Neem contact op", - "current-version": "Huidige versie", - "current": "Huidig", - "available-version": "Beschikbare versie", - "available": "Beschikbaar", - "upgrade": "Upgraden", - "version-is-up-to-date": "Versie is up-to-date" - }, - "license-info": { - "title": "Licentie-informatie", - "view-all": "Bekijk alles", - "license-portal": "Licentieportaal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Apparaten", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } assets", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integraties", - "community-support": "Community-ondersteuning", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Onbeperkte datapunten en berichten", - "unlimited-api-calls": "Onbeperkte API-aanroepen" - }, "usage-info": { "title": "Gebruik", "entities": "Entiteiten", diff --git a/ui-ngx/src/assets/locale/locale.constant-no_NO.json b/ui-ngx/src/assets/locale/locale.constant-no_NO.json index a4436625e7..023f254b81 100644 --- a/ui-ngx/src/assets/locale/locale.constant-no_NO.json +++ b/ui-ngx/src/assets/locale/locale.constant-no_NO.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfigurer med AI", - "follow-up-prompt-placeholder": "Svar...", - "sub-title": "Jeg kan hjelpe deg med å sette opp og administrere enhetene, dashbordene, beregnede felt, alarmregler og varsler dine — bare beskriv hva du trenger, så ordner jeg resten.", "new-chat": "Ny chat", - "no-chats": "Ingen chatter ennå", "today": "I dag", "yesterday": "I går", "last-7-days": "Siste 7 dager", @@ -703,20 +700,12 @@ "delete-chat-title": "Er du sikker på at du vil slette '{{name}}'?", "delete-chat-text": "Alle chatmeldinger vil gå tapt", "delete-chat-confirm": "Ja, slett", - "action-approval-required": "Godkjenning av handling kreves", "approve": "Godkjenn", - "approve-all": "Godkjenn alle videre handlinger", "deny": "Avslå", - "processing": "Behandler...", "approved": "Ferdig", - "denied": "Avslått", "error": "Mislyktes", "thinking": "Tenker...", - "connection-lost": "Tilkoblingen til AI-assistenten ble brutt. Kobler til på nytt...", - "reconnect-failed": "Kunne ikke koble til AI-assistenten på nytt. Åpne chatten igjen for å se svaret.", - "rename-chat-title": "Gi nytt navn til denne chatten", - "export-chat": "Eksporter chat", - "main-title": "Hei! Jeg er AI-assistenten din" + "export-chat": "Eksporter chat" }, "alarm": { "alarm": "Alarm", @@ -11247,47 +11236,20 @@ "select-recaptcha-enterprise-service-account-file": "Dra og slipp filen med kontoopplysninger" }, "solution-creator": { - "ai-solution-creator": "AI-løsningsbygger", "describe-solution-you-want": "Beskriv løsningen du vil lage", - "enter-your-prompt": "Skriv inn prompten din", "target": "Mål", "install-solution": "Installer", - "solution-overview": "Løsningsoversikt: {{ name }}", - "dashboards-overview": "Dashbordoversikt: {{ name }}", - "entity-profile": "Entitetsprofil", - "entity-profiles": "Entitetsprofiler", - "name": "Navn", - "iam": "IAM", - "iam-full": "Identitets- og tilgangsstyring", - "table-view": "Tabell", - "schema-view": "Skjema", - "iam-info": "IAM-info", "operation": { "C": "Opprett", "R": "Les", "U": "Oppdater", "D": "Slett" }, - "alarm-info": "Alarminfo", "description": "Beskrivelse", - "data": "Data", - "entity-info": "Entitetsinfo", - "calculated-field-info": "Info om beregnet felt", - "field-type": "Felttype", - "scope": "Omfang", "delete-alarm-title": "Slette denne foreslåtte alarmen?", "delete-alarm-text": "Denne alarmen, som ble foreslått basert på beskrivelsen din, blir ikke lagt til i den foreslåtte løsningen.
    Du kan alltid redigere eller opprette alarmer på nytt manuelt senere. Denne handlingen kan ikke angres.", - "basic-mode": "Grunnleggende", - "advanced-mode": "Avansert", "create-solution": "Opprett løsning", "go-dashboard-manager": "Neste: Dashborddesign", - "success-generate-title": "Løsningen er klar!", - "success-generate-sub-title": "Du kan installere den på kontoen din ved å klikke på knappen nedenfor", - "success-generate-install-title": "Løsningen er installert!", - "success-generate-install-sub-title": "For å redigere løsningen må du først avinstallere den eksisterende instansen", - "main-title": "Hei! Jeg er AI-assistenten din", - "sub-title": "Jeg hjelper deg med å gjøre kravene dine om til en fullt fungerende IoT-løsning.\nBare beskriv hva du vil oppnå, så tar jeg meg av resten.", - "solutions": "Løsninger", "new-solution": "Ny løsning", "uninstall-solution": "Avinstaller", "uninstall-solution-dialog-title": "Er du sikker på at du vil avinstallere ‘{{ name }}’?", @@ -11297,12 +11259,8 @@ "delete-solution-text": "Alle dataene dine vil gå tapt", "delete-solution-confirm": "Ja, slett", "copy-solution": "Kopier løsning", - "expand-sidebar": "Utvid sidepanel", - "collapse-sidebar": "Skjul sidepanel", "solution-id": "Løsnings-ID", "solution-id-required": "Løsnings-ID er påkrevd", - "rename-solution-title": "Gi nytt navn til denne løsningen", - "generate-again": "Generer på nytt", "skip-interview": "Hopp over intervjuet", "update-solution": "Oppdater løsning", "finish-edit": "Fullfør redigering", @@ -11312,8 +11270,6 @@ "water-metering": "Vannmåling", "coffee-machine-monitoring": "Overvåking av kaffemaskiner", "fleet-geofencing": "Geofencing for kjøretøyflåte", - "more-examples": "Flere eksempler", - "hide": "Skjul", "solution-info": "Løsningsinformasjon", "solution-info-with-name": "Løsningsinformasjon: {{ name }}", "status": "Status", @@ -11326,14 +11282,8 @@ "info": "Info", "main-dashboard": "Hoveddashbord", "view-as": "Vis som {{ name }}", - "generated-by-calculated-field-name": "Generert av det beregnede feltet ‘{{ name }}’", "estimate-wait-time": "Estimert ventetid er ~{{ time }}", - "analyzing-your-request": "Analyserer forespørselen din...", "condition": "Betingelse", - "installing": "Installerer løsningen...", - "step-architecture-design": "Arkitekturdesign", - "step-dashboard-design": "Dashborddesign", - "step-solution-installation": "Installasjon av løsningen", "step-reading-device-data": "Leser enhetsdata…", "step-analyzing-telemetry-attributes": "Analyserer telemetri og attributter…", "step-selecting-widgets": "Velger widgeter for dataene dine…", @@ -11365,11 +11315,7 @@ "step-loading-building-alarm-rules": "Bygger alarmregler…", "step-loading-assembling-dashboards": "Setter sammen dashbord…", "step-loading-preparing-states": "Forbereder tilstander…", - "step-loading-initializing-solution": "Initialiserer løsningen…", - "ai-credits": "AI-kreditter", - "ai-credits-update": "Bytt plan", - "ai-credits-usage": "AI-kreditter: {{ used }} av {{ max }} brukt", - "ai-credits-description": "Du har brukt {{ used }} av dine {{ max }} AI-kreditter denne måneden. Grensen tilbakestilles {{ date }}. Kontakt systemadministratoren for å øke AI-kredittkvoten din." + "step-loading-initializing-solution": "Initialiserer løsningen…" }, "markdown": { "edit": "Rediger", @@ -13795,11 +13741,6 @@ "disk-warning-text": "Lite tilgjengelig diskplass. For å unngå datatap, frigjør eller utvid diskplassen.", "disk-critical-text": "Kritisk lite diskplass. For å unngå datatap, frigjør eller utvid diskplassen." }, - "cluster-info": { - "service-id": "Tjeneste-ID", - "service-type": "Tjenestetype", - "no-data": "Ingen data" - }, "transport-messages": { "title": "Transportmeldinger", "info": "Alle meldinger mottatt fra enheter" @@ -13838,41 +13779,9 @@ "no-last-viewed-dashboards": "Ingen nylig viste dashbord" }, "configured-features": { - "title": "Konfigurerte funksjoner", - "info": "Status for funksjoner som krever konfigurasjon", - "white-labeling-feature": "White labeling", - "email-feature": "E-post", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funksjonen er konfigurert.\nKlikk for å sette opp", "feature-not-configured": "Funksjonen er ikke konfigurert.\nKlikk for å sette opp" }, - "version-info": { - "title": "Versjon", - "contact-us": "Kontakt oss", - "current-version": "Gjeldende versjon", - "current": "Gjeldende", - "available-version": "Tilgjengelig versjon", - "available": "Tilgjengelig", - "upgrade": "Oppgrader", - "version-is-up-to-date": "Versjonen er oppdatert" - }, - "license-info": { - "title": "Lisensinformasjon", - "view-all": "Vis alle", - "license-portal": "Lisensportal", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } enheter", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } eiendeler", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge-instanser", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } dashbord", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integrasjoner", - "community-support": "Fellesskapsstøtte", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Ubegrensede datapunkter og meldinger", - "unlimited-api-calls": "Ubegrensede API-kall" - }, "usage-info": { "title": "Bruk", "entities": "Entiteter", diff --git a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json index 769c74e48c..419f7552a6 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json +++ b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Skonfiguruj z AI", - "follow-up-prompt-placeholder": "Odpowiedz...", - "sub-title": "Pomogę Ci skonfigurować Twoje urządzenia, pulpity, pola obliczeniowe, reguły alarmów i powiadomienia oraz zarządzać nimi — wystarczy, że opiszesz, czego potrzebujesz, a ja zajmę się resztą.", "new-chat": "Nowy czat", - "no-chats": "Brak czatów", "today": "Dzisiaj", "yesterday": "Wczoraj", "last-7-days": "Ostatnie 7 dni", @@ -703,17 +700,11 @@ "delete-chat-title": "Czy na pewno chcesz usunąć „{{name}}”?", "delete-chat-text": "Wszystkie wiadomości czatu zostaną utracone", "delete-chat-confirm": "Tak, usuń", - "action-approval-required": "Wymagane zatwierdzenie akcji", "approve": "Zatwierdź", - "approve-all": "Zatwierdź wszystkie kolejne działania", "deny": "Odrzuć", - "processing": "Przetwarzanie...", "approved": "Gotowe", - "denied": "Odrzucone", "error": "Niepowodzenie", "thinking": "Myślę...", - "connection-lost": "Utracono połączenie z asystentem AI. Ponowne łączenie...", - "reconnect-failed": "Nie udało się ponownie połączyć z asystentem AI. Otwórz czat ponownie, aby zobaczyć odpowiedź.", "ask-the-assistant": "Zapytaj asystenta AI", "send": "Wyślij", "new-line": "Nowy wiersz", @@ -740,9 +731,7 @@ "text": "Tekst", "file": "Plik" }, - "rename-chat-title": "Zmień nazwę tego czatu", - "export-chat": "Eksportuj czat", - "main-title": "Cześć! Jestem Twoim asystentem AI" + "export-chat": "Eksportuj czat" }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Zaproponuj reguły alarmów", @@ -11273,47 +11262,20 @@ "select-recaptcha-enterprise-service-account-file": "Przeciągnij i upuść plik z danymi uwierzytelniającymi Twojego konta" }, "solution-creator": { - "ai-solution-creator": "Kreator rozwiązań AI", "describe-solution-you-want": "Opisz rozwiązanie, które chcesz utworzyć", - "enter-your-prompt": "Wprowadź prompt", "target": "Cel", "install-solution": "Zainstaluj", - "solution-overview": "Przegląd rozwiązania: {{ name }}", - "dashboards-overview": "Przegląd pulpitów: {{ name }}", - "entity-profile": "Profil obiektu", - "entity-profiles": "Profile obiektów", - "name": "Nazwa", - "iam": "IAM", - "iam-full": "Zarządzanie tożsamością i dostępem", - "table-view": "Tabela", - "schema-view": "Schemat", - "iam-info": "Informacje o IAM", "operation": { "C": "Utwórz", "R": "Odczytaj", "U": "Aktualizuj", "D": "Usuń" }, - "alarm-info": "Informacje o alarmie", "description": "Opis", - "data": "Dane", - "entity-info": "Informacje o obiekcie", - "calculated-field-info": "Informacje o polu obliczeniowym", - "field-type": "Typ pola", - "scope": "Zakres", "delete-alarm-title": "Czy chcesz usunąć ten sugerowany alarm?", "delete-alarm-text": "Ten alarm, zasugerowany na podstawie Twojego opisu, nie zostanie dodany do proponowanej wersji rozwiązania.
    Alarmy możesz zawsze później edytować lub ręcznie utworzyć ponownie. Tej akcji nie można cofnąć.", - "basic-mode": "Podstawowy", - "advanced-mode": "Zaawansowany", "create-solution": "Utwórz rozwiązanie", "go-dashboard-manager": "Dalej: projekt pulpitu", - "success-generate-title": "Rozwiązanie jest gotowe!", - "success-generate-sub-title": "Możesz je zainstalować na swoim koncie, klikając przycisk poniżej", - "success-generate-install-title": "Rozwiązanie zostało zainstalowane!", - "success-generate-install-sub-title": "Aby edytować rozwiązanie, najpierw odinstaluj istniejącą instancję", - "main-title": "Cześć! Jestem Twoim asystentem AI", - "sub-title": "Pomagam Ci przekształcić Twoje wymagania w w pełni funkcjonalne rozwiązanie IoT.\nPo prostu opisz, co chcesz osiągnąć, a ja zajmę się resztą.", - "solutions": "Rozwiązania", "new-solution": "Nowe rozwiązanie", "uninstall-solution": "Odinstaluj", "uninstall-solution-dialog-title": "Czy na pewno chcesz odinstalować „{{ name }}”?", @@ -11323,12 +11285,8 @@ "delete-solution-text": "Wszystkie Twoje dane zostaną utracone", "delete-solution-confirm": "Tak, usuń", "copy-solution": "Kopiuj rozwiązanie", - "expand-sidebar": "Rozwiń panel boczny", - "collapse-sidebar": "Zwiń panel boczny", "solution-id": "ID rozwiązania", "solution-id-required": "ID rozwiązania jest wymagane", - "rename-solution-title": "Zmień nazwę tego rozwiązania", - "generate-again": "Wygeneruj ponownie", "skip-interview": "Pomiń wywiad", "update-solution": "Aktualizuj rozwiązanie", "finish-edit": "Zakończ edycję", @@ -11338,8 +11296,6 @@ "water-metering": "Pomiar zużycia wody", "coffee-machine-monitoring": "Monitorowanie ekspresów do kawy", "fleet-geofencing": "Geofencing floty", - "more-examples": "Więcej przykładów", - "hide": "Ukryj", "solution-info": "Informacje o rozwiązaniu", "solution-info-with-name": "Informacje o rozwiązaniu: {{ name }}", "status": "Status", @@ -11352,14 +11308,8 @@ "info": "Informacje", "main-dashboard": "Pulpit główny", "view-as": "Wyświetl jako {{ name }}", - "generated-by-calculated-field-name": "Wygenerowano przez pole obliczeniowe „{{ name }}”", "estimate-wait-time": "Szacowany czas oczekiwania: ~{{ time }}", - "analyzing-your-request": "Analizowanie Twojego zapytania...", "condition": "Warunek", - "installing": "Instalowanie rozwiązania...", - "step-architecture-design": "Projekt architektury", - "step-dashboard-design": "Projekt pulpitu", - "step-solution-installation": "Instalacja rozwiązania", "step-reading-device-data": "Odczytywanie danych urządzenia…", "step-analyzing-telemetry-attributes": "Analizowanie telemetrii i atrybutów…", "step-selecting-widgets": "Wybieranie widżetów dla Twoich danych…", @@ -11391,11 +11341,7 @@ "step-loading-building-alarm-rules": "Tworzenie reguł alarmów…", "step-loading-assembling-dashboards": "Składanie pulpitów…", "step-loading-preparing-states": "Przygotowywanie stanów…", - "step-loading-initializing-solution": "Inicjowanie rozwiązania…", - "ai-credits": "Kredyty AI", - "ai-credits-update": "Zmień plan", - "ai-credits-usage": "Kredyty AI: wykorzystano {{ used }} z {{ max }}", - "ai-credits-description": "W tym miesiącu wykorzystano {{ used }} z {{ max }} Twoich kredytów AI. Limit zostanie zresetowany {{ date }}. Aby zwiększyć limit kredytów AI, skontaktuj się z administratorem systemu." + "step-loading-initializing-solution": "Inicjowanie rozwiązania…" }, "markdown": { "edit": "Edytuj", @@ -13821,11 +13767,6 @@ "disk-warning-text": "Kończy się miejsce na dysku. Aby zapobiec utracie danych, zwolnij lub zwiększ miejsce na dysku.", "disk-critical-text": "Krytycznie mało miejsca na dysku. Aby zapobiec utracie danych, zwolnij lub zwiększ miejsce na dysku." }, - "cluster-info": { - "service-id": "Identyfikator usługi", - "service-type": "Rodzaj usługi", - "no-data": "Brak danych" - }, "transport-messages": { "title": "Wiadomości transportowe", "info": "Wszystkie wiadomości pochodzące z urządzeń" @@ -13864,41 +13805,9 @@ "no-last-viewed-dashboards": "Nie ma jeszcze ostatnio oglądanych pulpitów" }, "configured-features": { - "title": "Skonfigurowane funkcje", - "info": "Stan funkcji wymagających konfiguracji", - "white-labeling-feature": "Branding", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Funkcja jest skonfigurowana.\nKliknij, aby skonfigurować", "feature-not-configured": "Funkcja nie jest skonfigurowana.\nKliknij, aby skonfigurować" }, - "version-info": { - "title": "Wersja", - "contact-us": "Skontaktuj się z nami", - "current-version": "Bieżąca wersja", - "current": "Bieżąca", - "available-version": "Dostępna wersja", - "available": "Dostępna", - "upgrade": "Uaktualnij", - "version-is-up-to-date": "Wersja jest aktualna" - }, - "license-info": { - "title": "Informacje o licencji", - "view-all": "Pokaż wszystkie", - "license-portal": "Portal licencyjny", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } urządzeń", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } zasobów", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } instancji Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } pulpitów", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } integracji", - "community-support": "Pomoc społeczności", - "white-labeling": "Branding", - "unlimited-datapoints-and-messages": "Nieograniczone punkty danych i wiadomości", - "unlimited-api-calls": "Nieograniczone wywołania API" - }, "usage-info": { "title": "Wykorzystanie", "entities": "Obiekty", diff --git a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json index d7a2cdf625..c133e839ea 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json +++ b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurar com IA", - "follow-up-prompt-placeholder": "Responder...", - "sub-title": "Posso ajudá-lo a configurar e gerenciar seus dispositivos, dashboards, campos calculados, regras de alarme e notificações — basta descrever o que você precisa e eu cuido do resto.", "new-chat": "Novo chat", - "no-chats": "Nenhum chat ainda", "today": "Hoje", "yesterday": "Ontem", "last-7-days": "Últimos 7 dias", @@ -703,18 +700,12 @@ "delete-chat-title": "Tem certeza de que deseja excluir '{{name}}'?", "delete-chat-text": "Todas as mensagens do chat serão perdidas", "delete-chat-confirm": "Sim, excluir", - "action-approval-required": "Aprovação da ação necessária", "approve": "Aprovar", - "approve-all": "Aprovar todas as próximas ações", "deny": "Negar", - "processing": "Processando...", "approved": "Concluído", - "denied": "Negado", "error": "Falhou", "thinking": "Pensando...", - "rename-chat-title": "Renomear este chat", - "export-chat": "Exportar chat", - "main-title": "Olá! Eu sou seu assistente de IA" + "export-chat": "Exportar chat" }, "alarm": { "alarm": "Alarme", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Arraste e solte seu arquivo de credenciais da conta" }, "solution-creator": { - "ai-solution-creator": "Criador de soluções com IA", "describe-solution-you-want": "Descreva a solução que você deseja criar", - "enter-your-prompt": "Insira seu prompt", "target": "Destino", "install-solution": "Instalar", - "solution-overview": "Visão geral da solução: {{ name }}", - "dashboards-overview": "Visão geral dos dashboards: {{ name }}", - "entity-profile": "Perfil de entidade", - "entity-profiles": "Perfis de entidade", - "name": "Nome", - "iam": "IAM", - "iam-full": "Gerenciamento de identidade e acesso", - "table-view": "Tabela", - "schema-view": "Esquema", - "iam-info": "Informações de IAM", "operation": { "C": "Criar", "R": "Ler", "U": "Modificar", "D": "Excluir" }, - "alarm-info": "Informações do alarme", "description": "Descrição", - "data": "Dados", - "entity-info": "Informações da entidade", - "calculated-field-info": "Informações do campo calculado", - "field-type": "Tipo de campo", - "scope": "Escopo", "delete-alarm-title": "Excluir este alarme sugerido?", "delete-alarm-text": "Este alarme, sugerido com base na sua descrição, não será adicionado à solução proposta.
    Você sempre pode editar ou recriar alarmes manualmente mais tarde. Esta ação não pode ser desfeita.", - "basic-mode": "Básico", - "advanced-mode": "Avançado", "create-solution": "Criar solução", "go-dashboard-manager": "Próximo: design do dashboard", - "success-generate-title": "A solução está pronta!", - "success-generate-sub-title": "Você pode instalá-la na sua conta clicando no botão abaixo", - "success-generate-install-title": "Solução instalada!", - "success-generate-install-sub-title": "Para editar a solução, primeiro desinstale a instância existente", - "main-title": "Olá! Sou seu assistente de IA", - "sub-title": "Ajudo você a transformar seus requisitos em uma solução de IoT totalmente funcional.\nBasta descrever o que deseja alcançar, e eu cuido do resto.", - "solutions": "Soluções", "new-solution": "Nova solução", "uninstall-solution": "Desinstalar", "uninstall-solution-dialog-title": "Tem certeza de que deseja desinstalar ‘{{ name }}’?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Todos os seus dados serão perdidos", "delete-solution-confirm": "Sim, excluir", "copy-solution": "Copiar solução", - "expand-sidebar": "Expandir barra lateral", - "collapse-sidebar": "Recolher barra lateral", "solution-id": "ID da solução", "solution-id-required": "O ID da solução é obrigatório", - "rename-solution-title": "Renomear esta solução", - "generate-again": "Gerar novamente", "skip-interview": "Ignorar entrevista", "update-solution": "Atualizar solução", "finish-edit": "Concluir edição", @@ -11298,8 +11258,6 @@ "water-metering": "Medição de água", "coffee-machine-monitoring": "Monitoramento de máquinas de café", "fleet-geofencing": "Geofencing de frota", - "more-examples": "Mais exemplos", - "hide": "Ocultar", "solution-info": "Informações da solução", "solution-info-with-name": "Informações da solução: {{ name }}", "status": "Status", @@ -11312,14 +11270,8 @@ "info": "Informações", "main-dashboard": "Dashboard principal", "view-as": "Visualizar como {{ name }}", - "generated-by-calculated-field-name": "Gerado pelo campo calculado ‘{{ name }}’", "estimate-wait-time": "O tempo de espera estimado é de ~{{ time }}", - "analyzing-your-request": "Analisando sua solicitação...", "condition": "Condição", - "installing": "Instalando a solução...", - "step-architecture-design": "Design da arquitetura", - "step-dashboard-design": "Design do dashboard", - "step-solution-installation": "Instalação da solução", "step-reading-device-data": "Lendo dados do dispositivo…", "step-analyzing-telemetry-attributes": "Analisando telemetria e atributos…", "step-selecting-widgets": "Selecionando widgets para seus dados…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Construindo regras de alarme…", "step-loading-assembling-dashboards": "Montando dashboards…", "step-loading-preparing-states": "Preparando estados…", - "step-loading-initializing-solution": "Inicializando a solução…", - "ai-credits": "Créditos de IA", - "ai-credits-update": "Alterar plano", - "ai-credits-usage": "Créditos de IA: {{ used }} de {{ max }} usados", - "ai-credits-description": "Você usou {{ used }} dos seus {{ max }} créditos de IA este mês. O limite será redefinido em {{ date }}. Para aumentar sua cota de créditos de IA, entre em contato com o administrador do sistema." + "step-loading-initializing-solution": "Inicializando a solução…" }, "markdown": { "edit": "Editar", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Pouco espaço em disco. Para evitar perda de dados, libere ou expanda o espaço em disco.", "disk-critical-text": "Espaço em disco criticamente baixo. Para evitar perda de dados, libere ou expanda o espaço em disco." }, - "cluster-info": { - "service-id": "Id do serviço", - "service-type": "Tipo de serviço", - "no-data": "Sem dados" - }, "transport-messages": { "title": "Mensagens de transporte", "info": "Todas as mensagens recebidas dos dispositivos" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Nenhum Dashboard visualizado recentemente" }, "configured-features": { - "title": "Recursos configurados", - "info": "Status dos recursos que requerem configuração", - "white-labeling-feature": "Personalização de marca", - "email-feature": "E-mail", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Recurso está configurado.\nClique para configurar", "feature-not-configured": "Recurso não está configurado.\nClique para configurar" }, - "version-info": { - "title": "Versão", - "contact-us": "Fale conosco", - "current-version": "Versão atual", - "current": "Atual", - "available-version": "Versão disponível", - "available": "Disponível", - "upgrade": "Atualizar versão", - "version-is-up-to-date": "Versão está atualizada" - }, - "license-info": { - "title": "Informações de licença", - "view-all": "Ver todos", - "license-portal": "Portal de licenças", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Dispositivos", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Ativos", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edges", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Dashboards", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Integrações", - "community-support": "Suporte da comunidade", - "white-labeling": "Personalização de marca", - "unlimited-datapoints-and-messages": "Datapoints e mensagens ilimitados", - "unlimited-api-calls": "Chamadas de API ilimitadas" - }, "usage-info": { "title": "Uso", "entities": "Entidades", diff --git a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json index 3e904b23b0..1b895dc926 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json +++ b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json @@ -111,10 +111,7 @@ }, "ai-assistant": { "configure-with-ai": "Configurează cu IA", - "follow-up-prompt-placeholder": "Răspunde...", - "sub-title": "Vă pot ajuta să configurați și să gestionați dispozitivele, tablourile de bord, câmpurile calculate, regulile de alarmă și notificările — descrieți doar ce aveți nevoie, iar eu mă ocup de rest.", "new-chat": "Conversație nouă", - "no-chats": "Încă nu există conversații", "today": "Astăzi", "yesterday": "Ieri", "last-7-days": "Ultimele 7 zile", @@ -122,16 +119,11 @@ "delete-chat-title": "Sigur vrei să ștergi '{{name}}'?", "delete-chat-text": "Toate mesajele din conversație vor fi pierdute", "delete-chat-confirm": "Da, șterge", - "action-approval-required": "Este necesară aprobarea acțiunii", "approve": "Aprobă", "deny": "Refuză", - "processing": "Procesare...", "approved": "Terminat", - "denied": "Refuzat", "error": "Eșuat", - "thinking": "Mă gândesc...", - "rename-chat-title": "Redenumește această conversație", - "main-title": "Bună! Sunt asistentul tău IA" + "thinking": "Mă gândesc..." }, "alarm-rule": { "ai-assistant-example-suggest-rules-label": "Sugerează reguli de alarmă", diff --git a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json index db258613f3..8e62ad240a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-sl_SI.json +++ b/ui-ngx/src/assets/locale/locale.constant-sl_SI.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Konfiguriraj z AI", - "follow-up-prompt-placeholder": "Odgovori...", - "sub-title": "Pomagam vam surove telemetrične podatke spremeniti v smiselne uvide. Preprosto opišite, kaj želite doseči, in jaz bom poskrbel za ostalo.", "new-chat": "Nov klepet", - "no-chats": "Še ni klepetov", "today": "Danes", "yesterday": "Včeraj", "last-7-days": "Zadnjih 7 dni", @@ -703,17 +700,11 @@ "delete-chat-title": "Ali ste prepričani, da želite izbrisati »{{name}}«?", "delete-chat-text": "Vsa sporočila klepeta bodo izgubljena", "delete-chat-confirm": "Da, izbriši", - "action-approval-required": "Potrebna je odobritev dejanja", "approve": "Odobri", - "approve-all": "Odobri vsa nadaljnja dejanja", "deny": "Zavrni", - "processing": "Obdelovanje...", "approved": "Končano", - "denied": "Zavrnjeno", "error": "Ni uspelo", "thinking": "Razmišljam...", - "connection-lost": "Povezava s pomočnikom AI je bila prekinjena. Ponovno vzpostavljanje povezave...", - "reconnect-failed": "Ponovna povezava s pomočnikom AI ni uspela. Znova odprite klepet, da vidite njegov odgovor.", "ask-the-assistant": "Vprašaj pomočnika AI", "send": "Pošlji", "new-line": "Nova vrstica", @@ -740,9 +731,7 @@ "text": "Besedilo", "file": "Datoteka" }, - "rename-chat-title": "Preimenuj ta klepet", - "export-chat": "Izvozi klepet", - "main-title": "Pozdravljeni! Jaz sem vaš AI-pomočnik" + "export-chat": "Izvozi klepet" }, "alarm": { "alarm": "Alarm", @@ -11344,47 +11333,20 @@ "select-recaptcha-enterprise-service-account-file": "Povlecite in spustite datoteko s poverilnicami računa" }, "solution-creator": { - "ai-solution-creator": "Ustvarjalnik rešitev AI", "describe-solution-you-want": "Opišite rešitev, ki jo želite ustvariti", - "enter-your-prompt": "Vnesite poziv", "target": "Cilj", "install-solution": "Namesti", - "solution-overview": "Pregled rešitve: {{ name }}", - "dashboards-overview": "Pregled nadzornih plošč: {{ name }}", - "entity-profile": "Profil entitete", - "entity-profiles": "Profili entitet", - "name": "Ime", - "iam": "IAM", - "iam-full": "Upravljanje identitet in dostopa", - "table-view": "Tabela", - "schema-view": "Shema", - "iam-info": "Informacije o IAM", "operation": { "C": "Ustvari", "R": "Preberi", "U": "Posodobi", "D": "Izbriši" }, - "alarm-info": "Informacije o alarmu", "description": "Opis", - "data": "Podatki", - "entity-info": "Informacije o entiteti", - "calculated-field-info": "Informacije o izračunanem polju", - "field-type": "Vrsta polja", - "scope": "Obseg", "delete-alarm-title": "Ali želite izbrisati ta predlagani alarm?", "delete-alarm-text": "Ta alarm, predlagan na podlagi vašega opisa, ne bo dodan v predlagano rešitev.
    Alarme lahko kadar koli pozneje ročno uredite ali znova ustvarite. Tega dejanja ni mogoče razveljaviti.", - "basic-mode": "Osnovno", - "advanced-mode": "Napredno", "create-solution": "Ustvari rešitev", "go-dashboard-manager": "Naprej: oblikovanje nadzorne plošče", - "success-generate-title": "Rešitev je pripravljena!", - "success-generate-sub-title": "Namestite jo lahko v svoj račun s klikom na spodnji gumb", - "success-generate-install-title": "Rešitev je nameščena!", - "success-generate-install-sub-title": "Če želite urediti rešitev, najprej odstranite obstoječo namestitev", - "main-title": "Pozdravljeni! Jaz sem vaš AI-pomočnik", - "sub-title": "Pomagam vam pretvoriti vaše zahteve v popolnoma delujočo rešitev IoT.\nSamo opišite, kaj želite doseči, za vse drugo pa bom poskrbel jaz.", - "solutions": "Rešitve", "new-solution": "Nova rešitev", "uninstall-solution": "Odstrani namestitev", "uninstall-solution-dialog-title": "Ali ste prepričani, da želite odstraniti »{{ name }}«?", @@ -11394,12 +11356,8 @@ "delete-solution-text": "Vsi vaši podatki bodo izgubljeni", "delete-solution-confirm": "Da, izbriši", "copy-solution": "Kopiraj rešitev", - "expand-sidebar": "Razširi stransko vrstico", - "collapse-sidebar": "Strni stransko vrstico", "solution-id": "ID rešitve", "solution-id-required": "ID rešitve je obvezen", - "rename-solution-title": "Preimenuj to rešitev", - "generate-again": "Ustvari znova", "skip-interview": "Preskoči intervju", "update-solution": "Posodobi rešitev", "finish-edit": "Zaključi urejanje", @@ -11409,8 +11367,6 @@ "water-metering": "Merjenje porabe vode", "coffee-machine-monitoring": "Spremljanje kavnega avtomata", "fleet-geofencing": "Geografsko ograjevanje voznega parka", - "more-examples": "Več primerov", - "hide": "Skrij", "solution-info": "Podatki o rešitvi", "solution-info-with-name": "Podatki o rešitvi: {{ name }}", "status": "Stanje", @@ -11423,14 +11379,8 @@ "info": "Informacije", "main-dashboard": "Glavna nadzorna plošča", "view-as": "Prikaži kot {{ name }}", - "generated-by-calculated-field-name": "Ustvarjeno z izračunanim poljem »{{ name }}«", "estimate-wait-time": "Predviden čas čakanja je ~{{ time }}", - "analyzing-your-request": "Analiziranje vaše zahteve...", "condition": "Pogoj", - "installing": "Nameščanje rešitve...", - "step-architecture-design": "Načrtovanje arhitekture", - "step-dashboard-design": "Oblikovanje nadzorne plošče", - "step-solution-installation": "Namestitev rešitve", "step-reading-device-data": "Branje podatkov naprave…", "step-analyzing-telemetry-attributes": "Analiziranje telemetrije in atributov…", "step-selecting-widgets": "Izbiranje gradnikov za vaše podatke…", @@ -11462,11 +11412,7 @@ "step-loading-building-alarm-rules": "Gradnja pravil za alarme…", "step-loading-assembling-dashboards": "Sestavljanje nadzornih plošč…", "step-loading-preparing-states": "Pripravljanje stanj…", - "step-loading-initializing-solution": "Inicializacija rešitve…", - "ai-credits": "Krediti AI", - "ai-credits-update": "Nadgradi paket", - "ai-credits-usage": "Krediti AI: porabljeno {{ used }} od {{ max }}", - "ai-credits-description": "Ta mesec ste porabili {{ used }} od svojih {{ max }} kreditov AI. Omejitev se ponastavi {{ date }}. Če želite povečati količino kreditov AI, se obrnite na svojega sistemskega administratorja." + "step-loading-initializing-solution": "Inicializacija rešitve…" }, "widgets": { "mobile-app-qr-code": { @@ -13810,11 +13756,6 @@ "disk-warning-text": "Na disku primanjkuje prostora. Da preprečite izgubo podatkov, sprostite ali razširite prostor na disku.", "disk-critical-text": "Prostora na disku je kritično malo. Da preprečite izgubo podatkov, sprostite ali razširite prostor na disku." }, - "cluster-info": { - "service-id": "ID storitve", - "service-type": "Vrsta storitve", - "no-data": "Ni podatkov" - }, "transport-messages": { "title": "Transportna sporočila", "info": "Vsa sporočila, prejeta iz naprav" @@ -13853,41 +13794,9 @@ "no-last-viewed-dashboards": "Ogledanih nadzornih plošč še ni" }, "configured-features": { - "title": "Konfigurirane funkcije", - "info": "Stanje funkcij, ki zahtevajo konfiguracijo", - "white-labeling-feature": "Prilagajanje znamke", - "email-feature": "E-pošta", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2.0", - "2fa-feature": "2FA", "feature-configured": "Funkcija je konfigurirana.\nKliknite za nastavitev", "feature-not-configured": "Funkcija ni konfigurirana.\nKliknite za nastavitev" }, - "version-info": { - "title": "Različica", - "contact-us": "Stik z nami", - "current-version": "Trenutna različica", - "current": "Trenutna", - "available-version": "Razpoložljiva različica", - "available": "Razpoložljiva", - "upgrade": "Nadgradi", - "version-is-up-to-date": "Različica je posodobljena" - }, - "license-info": { - "title": "Podatki o licenci", - "view-all": "Prikaži vse", - "license-portal": "Portal za licence", - "devices-info": "{count} / { max, plural, =0 {∞ naprav} one {# naprava} two {# napravi} few {# naprave} other {# naprav} }", - "assets-info": "{count} / { max, plural, =0 {∞ sredstev} one {# sredstvo} two {# sredstvi} few {# sredstva} other {# sredstev} }", - "edges-info": "{count} / { max, plural, =0 {∞ instanc Edge} one {# instanca Edge} two {# instanci Edge} few {# instance Edge} other {# instanc Edge} }", - "dashboards-info": "{count} / { max, plural, =0 {∞ nadzornih plošč} one {# nadzorna plošča} two {# nadzorni plošči} few {# nadzorne plošče} other {# nadzornih plošč} }", - "integrations-info": "{count} / { max, plural, =0 {∞ integracij} one {# integracija} two {# integraciji} few {# integracije} other {# integracij} }", - "community-support": "Podpora skupnosti", - "white-labeling": "Prilagajanje znamke", - "unlimited-datapoints-and-messages": "Neomejeno število podatkovnih točk in sporočil", - "unlimited-api-calls": "Neomejeno število klicev API" - }, "usage-info": { "title": "Uporaba", "entities": "Entitete", diff --git a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json index e9337b2a7f..e0c325cca4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json +++ b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Yapay zeka ile yapılandır", - "follow-up-prompt-placeholder": "Yanıtla...", - "sub-title": "Cihazlarınızı, panolarınızı, hesaplanmış alanlarınızı, alarm kurallarınızı ve bildirimlerinizi kurmanıza ve yönetmenize yardımcı olabilirim — ne istediğinizi açıklamanız yeterli, gerisini ben hallederim.", "new-chat": "Yeni sohbet", - "no-chats": "Henüz sohbet yok", "today": "Bugün", "yesterday": "Dün", "last-7-days": "Son 7 gün", @@ -703,20 +700,12 @@ "delete-chat-title": "'{{name}}' sohbetini silmek istediğinizden emin misiniz?", "delete-chat-text": "Tüm sohbet mesajları kaybolacak", "delete-chat-confirm": "Evet, sil", - "action-approval-required": "İşlem onayı gerekli", "approve": "Onayla", - "approve-all": "Sonraki tüm eylemleri onayla", "deny": "Reddet", - "processing": "İşleniyor...", "approved": "Tamamlandı", - "denied": "Reddedildi", "error": "Başarısız", "thinking": "Düşünüyor...", - "connection-lost": "Yapay zeka asistanı ile bağlantı kesildi. Yeniden bağlanılıyor...", - "reconnect-failed": "Yapay zeka asistanına yeniden bağlanılamadı. Yanıtını görmek için sohbeti yeniden açın.", - "rename-chat-title": "Bu sohbeti yeniden adlandır", - "export-chat": "Sohbeti dışa aktar", - "main-title": "Merhaba! Ben yapay zeka asistanınızım" + "export-chat": "Sohbeti dışa aktar" }, "alarm": { "alarm": "Alarm", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Hesap kimlik bilgileri dosyanızı sürükleyip bırakın" }, "solution-creator": { - "ai-solution-creator": "Yapay zeka çözüm oluşturucu", "describe-solution-you-want": "Oluşturmak istediğiniz çözümü açıklayın", - "enter-your-prompt": "İsteminizi girin", "target": "Hedef", "install-solution": "Kur", - "solution-overview": "Çözüm özeti: {{ name }}", - "dashboards-overview": "Panolara genel bakış: {{ name }}", - "entity-profile": "Öğe profili", - "entity-profiles": "Öğe profilleri", - "name": "Ad", - "iam": "IAM", - "iam-full": "Kimlik ve erişim yönetimi", - "table-view": "Tablo", - "schema-view": "Şema", - "iam-info": "IAM bilgisi", "operation": { "C": "Oluştur", "R": "Oku", "U": "Güncelle", "D": "Sil" }, - "alarm-info": "Alarm bilgisi", "description": "Açıklama", - "data": "Veri", - "entity-info": "Öğe bilgisi", - "calculated-field-info": "Hesaplanmış alan bilgisi", - "field-type": "Alan türü", - "scope": "Kapsam", "delete-alarm-title": "Önerilen bu alarm silinsin mi?", "delete-alarm-text": "Açıklamanıza göre önerilen bu alarm, önerilen çözüme eklenmeyecek.
    Alarmları daha sonra istediğiniz zaman manuel olarak düzenleyebilir veya yeniden oluşturabilirsiniz. Bu işlem geri alınamaz.", - "basic-mode": "Temel", - "advanced-mode": "Gelişmiş", "create-solution": "Çözüm oluştur", "go-dashboard-manager": "Sonraki: Pano tasarımı", - "success-generate-title": "Çözüm hazır!", - "success-generate-sub-title": "Aşağıdaki düğmeye tıklayarak çözümü hesabınıza kurabilirsiniz", - "success-generate-install-title": "Çözüm kuruldu!", - "success-generate-install-sub-title": "Çözümü düzenlemek için lütfen önce mevcut örneği kaldırın", - "main-title": "Merhaba! Ben yapay zeka asistanınızım", - "sub-title": "Gereksinimlerinizi tamamen işlevsel bir IoT çözümüne dönüştürmenize yardımcı olurum.\nNe yapmak istediğinizi açıklamanız yeterli, gerisini ben hallederim.", - "solutions": "Çözümler", "new-solution": "Yeni çözüm", "uninstall-solution": "Kaldır", "uninstall-solution-dialog-title": "‘{{ name }}’ adlı çözümü kaldırmak istediğinizden emin misiniz?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "Tüm verileriniz kaybolacak", "delete-solution-confirm": "Evet, sil", "copy-solution": "Çözümü kopyala", - "expand-sidebar": "Kenar çubuğunu genişlet", - "collapse-sidebar": "Kenar çubuğunu daralt", "solution-id": "Çözüm kimliği", "solution-id-required": "Çözüm kimliği gereklidir.", - "rename-solution-title": "Bu çözümü yeniden adlandır", - "generate-again": "Yeniden oluştur", "skip-interview": "Görüşmeyi atla", "update-solution": "Çözümü güncelle", "finish-edit": "Düzenlemeyi bitir", @@ -11300,8 +11258,6 @@ "water-metering": "Su sayacı ölçümü", "coffee-machine-monitoring": "Kahve makinesi izleme", "fleet-geofencing": "Filo coğrafi çitleme", - "more-examples": "Daha fazla örnek", - "hide": "Gizle", "solution-info": "Çözüm bilgisi", "solution-info-with-name": "Çözüm bilgisi: {{ name }}", "status": "Durum", @@ -11314,14 +11270,8 @@ "info": "Bilgi", "main-dashboard": "Ana pano", "view-as": "{{ name }} olarak görüntüle", - "generated-by-calculated-field-name": "‘{{ name }}’ hesaplanmış alanı tarafından oluşturuldu", "estimate-wait-time": "Tahmini bekleme süresi: ~{{ time }}", - "analyzing-your-request": "İsteğiniz analiz ediliyor...", "condition": "Koşul", - "installing": "Çözüm kuruluyor...", - "step-architecture-design": "Mimari tasarım", - "step-dashboard-design": "Pano tasarımı", - "step-solution-installation": "Çözüm kurulumu", "step-reading-device-data": "Cihaz verileri okunuyor…", "step-analyzing-telemetry-attributes": "Telemetri ve öznitelikler analiz ediliyor…", "step-selecting-widgets": "Verileriniz için widget'lar seçiliyor…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "Alarm kuralları oluşturuluyor…", "step-loading-assembling-dashboards": "Panolar oluşturuluyor…", "step-loading-preparing-states": "Durumlar hazırlanıyor…", - "step-loading-initializing-solution": "Çözüm başlatılıyor…", - "ai-credits": "Yapay zeka kredileri", - "ai-credits-update": "Planı güncelle", - "ai-credits-usage": "Yapay zeka kredileri: {{ used }} / {{ max }} kullanıldı", - "ai-credits-description": "Bu ay toplam {{ max }} yapay zeka kredinizden {{ used }} tanesini kullandınız. Limit {{ date }} tarihinde sıfırlanır. Yapay zeka kredisi kotanızı artırmak için lütfen sistem yöneticinize başvurun." + "step-loading-initializing-solution": "Çözüm başlatılıyor…" }, "markdown": { "edit": "Düzenle", @@ -13783,11 +13729,6 @@ "disk-warning-text": "Disk alanı azalıyor. Veri kaybını önlemek için disk alanını boşaltın veya genişletin.", "disk-critical-text": "Disk alanı kritik düzeyde düşük. Veri kaybını önlemek için disk alanını boşaltın veya genişletin." }, - "cluster-info": { - "service-id": "Servis kimliği", - "service-type": "Servis türü", - "no-data": "Veri yok" - }, "transport-messages": { "title": "Taşıma mesajları", "info": "Cihazlardan gelen tüm mesajlar" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "Henüz son görüntülenen pano yok" }, "configured-features": { - "title": "Yapılandırılmış özellikler", - "info": "Yapılandırma gerektiren özelliklerin durumu", - "white-labeling-feature": "White labeling", - "email-feature": "E-posta", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Özellik yapılandırıldı.\nAyarlamak için tıklayın", "feature-not-configured": "Özellik yapılandırılmadı.\nKurulum için tıklayın" }, - "version-info": { - "title": "Sürüm", - "contact-us": "Bize ulaşın", - "current-version": "Mevcut sürüm", - "current": "Mevcut", - "available-version": "Kullanılabilir sürüm", - "available": "Kullanılabilir", - "upgrade": "Yükselt", - "version-is-up-to-date": "Sürüm güncel" - }, - "license-info": { - "title": "Lisans bilgisi", - "view-all": "Tümünü görüntüle", - "license-portal": "Lisans portalı", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } Cihaz", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } Varlık", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } Pano", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } Entegrasyon", - "community-support": "Topluluk desteği", - "white-labeling": "White labeling", - "unlimited-datapoints-and-messages": "Sınırsız veri noktası ve mesaj", - "unlimited-api-calls": "Sınırsız API çağrısı" - }, "usage-info": { "title": "Kullanım", "entities": "Öğeler", diff --git a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json index c28f6da6fe..851397c032 100644 --- a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json +++ b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "Налаштувати за допомогою ШІ", - "follow-up-prompt-placeholder": "Відповісти...", - "sub-title": "Я можу допомогти вам налаштувати ваші пристрої, дашборди, обчислювані поля, правила тривог і сповіщення та керувати ними — просто опишіть, що вам потрібно, а решту я зроблю сам.", "new-chat": "Новий чат", - "no-chats": "Поки що немає чатів", "today": "Сьогодні", "yesterday": "Вчора", "last-7-days": "Останні 7 днів", @@ -703,18 +700,12 @@ "delete-chat-title": "Ви впевнені, що хочете видалити '{{name}}'?", "delete-chat-text": "Усі повідомлення чату буде втрачено", "delete-chat-confirm": "Так, видалити", - "action-approval-required": "Потрібне схвалення дії", "approve": "Схвалити", - "approve-all": "Схвалити всі подальші дії", "deny": "Відхилити", - "processing": "Обробка...", "approved": "Готово", - "denied": "Відхилено", "error": "Не вдалося", "thinking": "Думаю...", - "rename-chat-title": "Перейменувати цей чат", - "export-chat": "Експортувати чат", - "main-title": "Привіт! Я ваш ШІ-асистент" + "export-chat": "Експортувати чат" }, "alarm": { "alarm": "Тривога", @@ -11233,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "Перетягніть і відпустіть файл облікових даних вашого облікового запису" }, "solution-creator": { - "ai-solution-creator": "Конструктор рішень на основі ШІ", "describe-solution-you-want": "Опишіть рішення, яке ви хочете створити", - "enter-your-prompt": "Введіть свій запит", "target": "Ціль", "install-solution": "Встановити", - "solution-overview": "Огляд рішення: {{ name }}", - "dashboards-overview": "Огляд дашбордів: {{ name }}", - "entity-profile": "Профіль сутності", - "entity-profiles": "Профілі сутностей", - "name": "Назва", - "iam": "IAM", - "iam-full": "Керування ідентифікацією та доступом", - "table-view": "Таблиця", - "schema-view": "Схема", - "iam-info": "Інформація про IAM", "operation": { "C": "Створити", "R": "Читати", "U": "Змінити", "D": "Видалити" }, - "alarm-info": "Інформація про тривогу", "description": "Опис", - "data": "Дані", - "entity-info": "Інформація про сутність", - "calculated-field-info": "Інформація про обчислюване поле", - "field-type": "Тип поля", - "scope": "Область", "delete-alarm-title": "Видалити цю запропоновану тривогу?", "delete-alarm-text": "Ця тривога, запропонована на основі вашого опису, не буде додана до запропонованої збірки рішення.
    Ви завжди можете відредагувати або повторно створити тривоги вручну пізніше. Цю дію неможливо скасувати.", - "basic-mode": "Базовий", - "advanced-mode": "Розширений", "create-solution": "Створити рішення", "go-dashboard-manager": "Далі: дизайн дашборду", - "success-generate-title": "Рішення готове!", - "success-generate-sub-title": "Ви можете встановити це у своєму акаунті, натиснувши кнопку нижче", - "success-generate-install-title": "Рішення встановлено!", - "success-generate-install-sub-title": "Щоб редагувати рішення, спочатку видаліть наявний екземпляр", - "main-title": "Привіт! Я ваш ШІ-асистент", - "sub-title": "Я допоможу вам перетворити ваші вимоги на повністю функціональне IoT-рішення.\nПросто опишіть, чого ви хочете досягти, а решту я візьму на себе.", - "solutions": "Рішення", "new-solution": "Нове рішення", "uninstall-solution": "Деінсталювати", "uninstall-solution-dialog-title": "Ви впевнені, що хочете деінсталювати «{{ name }}»?", @@ -11283,12 +11247,8 @@ "delete-solution-text": "Усі ваші дані буде втрачено", "delete-solution-confirm": "Так, видалити", "copy-solution": "Копіювати рішення", - "expand-sidebar": "Розгорнути бічну панель", - "collapse-sidebar": "Згорнути бічну панель", "solution-id": "Ідентифікатор рішення", "solution-id-required": "Потрібно вказати ідентифікатор рішення", - "rename-solution-title": "Перейменувати це рішення", - "generate-again": "Згенерувати ще раз", "skip-interview": "Пропустити опитування", "update-solution": "Оновити рішення", "finish-edit": "Завершити редагування", @@ -11298,8 +11258,6 @@ "water-metering": "Облік водоспоживання", "coffee-machine-monitoring": "Моніторинг кавомашин", "fleet-geofencing": "Геозонування автопарку", - "more-examples": "Більше прикладів", - "hide": "Приховати", "solution-info": "Інформація про рішення", "solution-info-with-name": "Інформація про рішення: {{ name }}", "status": "Статус", @@ -11312,14 +11270,8 @@ "info": "Інформація", "main-dashboard": "Головний дашборд", "view-as": "Переглянути як {{ name }}", - "generated-by-calculated-field-name": "Згенеровано обчислюваним полем «{{ name }}»", "estimate-wait-time": "Орієнтовний час очікування: ~{{ time }}", - "analyzing-your-request": "Аналізуємо ваш запит...", "condition": "Умова", - "installing": "Встановлення рішення...", - "step-architecture-design": "Проєктування архітектури", - "step-dashboard-design": "Проєктування дашборду", - "step-solution-installation": "Встановлення рішення", "step-reading-device-data": "Читання даних пристрою…", "step-analyzing-telemetry-attributes": "Аналіз телеметрії та атрибутів…", "step-selecting-widgets": "Підбір віджетів для ваших даних…", @@ -11351,11 +11303,7 @@ "step-loading-building-alarm-rules": "Створення правил тривог…", "step-loading-assembling-dashboards": "Складання дашбордів…", "step-loading-preparing-states": "Підготовка станів…", - "step-loading-initializing-solution": "Ініціалізація рішення…", - "ai-credits": "Кредити ШІ", - "ai-credits-update": "Зберегти зміни", - "ai-credits-usage": "Кредити ШІ: використано {{ used }} з {{ max }}", - "ai-credits-description": "Ви використали {{ used }} з {{ max }} кредитів ШІ цього місяця. Ліміт скидається {{ date }}. Щоб збільшити ліміт кредитів ШІ, зверніться до системного адміністратора." + "step-loading-initializing-solution": "Ініціалізація рішення…" }, "markdown": { "edit": "Редагувати", @@ -13780,11 +13728,6 @@ "disk-warning-text": "Мало місця на диску. Щоб уникнути втрати даних, звільніть або розширте дисковий простір.", "disk-critical-text": "Критично мало місця на диску. Щоб уникнути втрати даних, звільніть або розширте дисковий простір." }, - "cluster-info": { - "service-id": "Id сервісу", - "service-type": "Тип сервісу", - "no-data": "Немає даних" - }, "transport-messages": { "title": "Транспортні повідомлення", "info": "Усі повідомлення, що надійшли від пристроїв" @@ -13823,41 +13766,9 @@ "no-last-viewed-dashboards": "Поки немає нещодавно переглянутих дашбордів" }, "configured-features": { - "title": "Налаштовані можливості", - "info": "Статус можливостей, що потребують налаштування", - "white-labeling-feature": "Брендування", - "email-feature": "Email", - "sms-feature": "SMS", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "2FA", "feature-configured": "Функцію налаштовано.\nНатисніть, щоб налаштувати", "feature-not-configured": "Функцію не налаштовано.\nНатисніть, щоб налаштувати" }, - "version-info": { - "title": "Версія", - "contact-us": "Зв’язатися з нами", - "current-version": "Поточна версія", - "current": "Поточна", - "available-version": "Доступна версія", - "available": "Доступна", - "upgrade": "Оновити версію", - "version-is-up-to-date": "Версія актуальна" - }, - "license-info": { - "title": "Інформація про ліцензію", - "view-all": "Переглянути все", - "license-portal": "Портал ліцензій", - "devices-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Пристрої", - "assets-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Активи", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Дашборди", - "integrations-info": "{count} / { max, plural, =0 {∞} one {#} few {#} other {#} } Інтеграції", - "community-support": "Підтримка спільноти", - "white-labeling": "Брендування", - "unlimited-datapoints-and-messages": "Необмежені точки даних і повідомлення", - "unlimited-api-calls": "Необмежені виклики API" - }, "usage-info": { "title": "Використання", "entities": "Сутності", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json index 74fedf0f9a..6af47c0059 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json @@ -692,10 +692,7 @@ }, "ai-assistant": { "configure-with-ai": "使用 AI 配置", - "follow-up-prompt-placeholder": "回复...", - "sub-title": "我可以帮助您设置和管理您的设备、仪表板、计算字段、告警规则和通知——只需描述您的需求,其余的交给我。", "new-chat": "新对话", - "no-chats": "暂无对话", "today": "今天", "yesterday": "昨天", "last-7-days": "最近 7 天", @@ -703,20 +700,12 @@ "delete-chat-title": "确定要删除 '{{name}}' 吗?", "delete-chat-text": "所有对话消息将丢失", "delete-chat-confirm": "是,删除", - "action-approval-required": "操作需要审批", "approve": "批准", - "approve-all": "批准后续所有操作", "deny": "拒绝", - "processing": "处理中...", "approved": "完成", - "denied": "已拒绝", "error": "失败", "thinking": "思考中...", - "connection-lost": "与 AI 助手的连接已断开。正在重新连接...", - "reconnect-failed": "无法重新连接到 AI 助手。请重新打开对话以查看其回复。", - "rename-chat-title": "重命名此对话", - "export-chat": "导出对话", - "main-title": "您好!我是您的 AI 助手" + "export-chat": "导出对话" }, "alarm": { "alarm": "告警", @@ -11235,47 +11224,20 @@ "select-recaptcha-enterprise-service-account-file": "拖放您的账户凭据文件" }, "solution-creator": { - "ai-solution-creator": "AI 解决方案创建器", "describe-solution-you-want": "描述您要创建的解决方案", - "enter-your-prompt": "输入提示词", "target": "目标", "install-solution": "安装", - "solution-overview": "解决方案概览:{{ name }}", - "dashboards-overview": "仪表板概览:{{ name }}", - "entity-profile": "实体配置", - "entity-profiles": "实体配置", - "name": "名称", - "iam": "IAM", - "iam-full": "身份和访问管理", - "table-view": "表格", - "schema-view": "架构", - "iam-info": "IAM 信息", "operation": { "C": "创建", "R": "读取", "U": "更新", "D": "删除" }, - "alarm-info": "告警信息", "description": "描述", - "data": "数据", - "entity-info": "实体信息", - "calculated-field-info": "计算字段信息", - "field-type": "字段类型", - "scope": "范围", "delete-alarm-title": "删除此建议告警?", "delete-alarm-text": "此告警是根据您的描述建议的,删除后将不会添加到拟构建的解决方案中。
    您以后随时可以手动编辑或重新创建告警。此操作无法撤销。", - "basic-mode": "基础", - "advanced-mode": "高级", "create-solution": "创建解决方案", "go-dashboard-manager": "下一步:仪表板设计", - "success-generate-title": "解决方案已就绪!", - "success-generate-sub-title": "点击下方按钮,即可将其安装到您的账户", - "success-generate-install-title": "解决方案已安装!", - "success-generate-install-sub-title": "如需编辑该解决方案,请先卸载现有实例", - "main-title": "您好!我是您的 AI 助手", - "sub-title": "我可以帮助您将需求转化为功能完备的物联网解决方案。\n只需描述您想实现的目标,其余的交给我。", - "solutions": "解决方案", "new-solution": "新建解决方案", "uninstall-solution": "卸载", "uninstall-solution-dialog-title": "确定要卸载“{{ name }}”吗?", @@ -11285,12 +11247,8 @@ "delete-solution-text": "您的所有数据都将丢失。", "delete-solution-confirm": "是,删除", "copy-solution": "复制解决方案", - "expand-sidebar": "展开侧边栏", - "collapse-sidebar": "收起侧边栏", "solution-id": "解决方案 ID", "solution-id-required": "解决方案 ID 为必填项。", - "rename-solution-title": "重命名此解决方案", - "generate-again": "重新生成", "skip-interview": "跳过问答", "update-solution": "更新解决方案", "finish-edit": "完成编辑", @@ -11300,8 +11258,6 @@ "water-metering": "水表计量", "coffee-machine-monitoring": "咖啡机监控", "fleet-geofencing": "车队地理围栏", - "more-examples": "更多示例", - "hide": "隐藏", "solution-info": "解决方案信息", "solution-info-with-name": "解决方案信息:{{ name }}", "status": "状态", @@ -11314,14 +11270,8 @@ "info": "信息", "main-dashboard": "主仪表板", "view-as": "以 {{ name }} 身份查看", - "generated-by-calculated-field-name": "由计算字段“{{ name }}”生成", "estimate-wait-time": "预计等待时间约为 {{ time }}", - "analyzing-your-request": "正在分析您的请求...", "condition": "条件", - "installing": "正在安装解决方案...", - "step-architecture-design": "架构设计", - "step-dashboard-design": "仪表板设计", - "step-solution-installation": "解决方案安装", "step-reading-device-data": "正在读取设备数据…", "step-analyzing-telemetry-attributes": "正在分析遥测和属性…", "step-selecting-widgets": "正在为您的数据选择部件…", @@ -11353,11 +11303,7 @@ "step-loading-building-alarm-rules": "正在构建告警规则…", "step-loading-assembling-dashboards": "正在组装仪表板…", "step-loading-preparing-states": "正在准备状态…", - "step-loading-initializing-solution": "正在初始化解决方案…", - "ai-credits": "AI 额度", - "ai-credits-update": "更改套餐", - "ai-credits-usage": "AI 额度:已使用 {{ used }}/{{ max }}", - "ai-credits-description": "本月您已使用 AI 额度 {{ used }}/{{ max }}。额度将于 {{ date }} 重置。如需提高 AI 额度,请联系系统管理员。" + "step-loading-initializing-solution": "正在初始化解决方案…" }, "markdown": { "edit": "编辑", @@ -13783,11 +13729,6 @@ "disk-warning-text": "磁盘空间不足。为避免数据丢失,请释放或扩展磁盘空间。", "disk-critical-text": "磁盘空间严重不足。为避免数据丢失,请释放或扩展磁盘空间。" }, - "cluster-info": { - "service-id": "服务 ID", - "service-type": "服务类型", - "no-data": "暂无数据" - }, "transport-messages": { "title": "传输消息", "info": "来自设备的所有消息" @@ -13826,41 +13767,9 @@ "no-last-viewed-dashboards": "暂无最近查看的仪表板" }, "configured-features": { - "title": "已配置功能", - "info": "需要配置的功能状态", - "white-labeling-feature": "白标", - "email-feature": "邮件", - "sms-feature": "短信", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "双因素认证", "feature-configured": "功能已配置。\n点击进行设置", "feature-not-configured": "功能未配置。\n点击进行设置" }, - "version-info": { - "title": "版本", - "contact-us": "联系我们", - "current-version": "当前版本", - "current": "当前", - "available-version": "可用版本", - "available": "可用", - "upgrade": "升级", - "version-is-up-to-date": "版本已是最新" - }, - "license-info": { - "title": "许可证信息", - "view-all": "查看全部", - "license-portal": "许可证门户", - "devices-info": "{count} / { max, plural, =0 {∞} other {#} } 设备", - "assets-info": "{count} / { max, plural, =0 {∞} other {#} } 资产", - "edges-info": "{count} / { max, plural, =0 {∞} other {#} } Edge", - "dashboards-info": "{count} / { max, plural, =0 {∞} other {#} } 仪表板", - "integrations-info": "{count} / { max, plural, =0 {∞} other {#} } 集成", - "community-support": "社区支持", - "white-labeling": "白标", - "unlimited-datapoints-and-messages": "无限数据点和消息", - "unlimited-api-calls": "无限 API 调用" - }, "usage-info": { "title": "使用情况", "entities": "实体", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json index 84e663026d..65f90b1de2 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_TW.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_TW.json @@ -7532,11 +7532,6 @@ "disk-warning-text": "磁碟空間不足。為避免資料遺失,請釋放或擴充磁碟空間。", "disk-critical-text": "磁碟空間嚴重不足。為避免資料遺失,請釋放或擴充磁碟空間。" }, - "cluster-info": { - "service-id": "服務識別碼", - "service-type": "服務類型", - "no-data": "尚無資料" - }, "transport-messages": { "title": "傳輸訊息", "info": "來自裝置的所有訊息" @@ -7575,26 +7570,8 @@ "no-last-viewed-dashboards": "尚無最近檢視的儀表板" }, "configured-features": { - "title": "已設定功能", - "info": "需要設定的功能狀態", - "email-feature": "電子郵件", - "sms-feature": "簡訊", - "slack-feature": "Slack", - "oauth2-feature": "OAuth 2", - "2fa-feature": "雙因素驗證", "feature-configured": "功能已設定。\n點選進行設定", - "feature-not-configured": "功能未設定。\n點選進行設定", - "white-labeling-feature": "白標" - }, - "version-info": { - "title": "版本", - "contact-us": "聯絡我們", - "current-version": "目前版本", - "current": "目前", - "available-version": "可用版本", - "available": "可用", - "upgrade": "升級", - "version-is-up-to-date": "版本已是最新" + "feature-not-configured": "功能未設定。\n點選進行設定" }, "usage-info": { "title": "使用情況", @@ -7774,20 +7751,6 @@ "align-top": "靠上對齊", "align-middle": "垂直置中", "align-bottom": "靠下對齊" - }, - "license-info": { - "title": "授權資訊", - "view-all": "檢視全部", - "license-portal": "授權入口網站", - "devices-info": "裝置:{count} / { max, plural, =0 {∞} other {#} }", - "assets-info": "資產:{count} / { max, plural, =0 {∞} other {#} }", - "edges-info": "Edge:{count} / { max, plural, =0 {∞} other {#} }", - "dashboards-info": "儀表板:{count} / { max, plural, =0 {∞} other {#} }", - "integrations-info": "整合:{count} / { max, plural, =0 {∞} other {#} }", - "community-support": "社群支援", - "white-labeling": "白標", - "unlimited-datapoints-and-messages": "不限資料點與訊息數量", - "unlimited-api-calls": "不限 API 呼叫次數" } }, "icon": { @@ -11476,10 +11439,7 @@ }, "ai-assistant": { "configure-with-ai": "使用 AI 設定", - "follow-up-prompt-placeholder": "回覆…", - "sub-title": "我可以協助您設定及管理裝置、儀表板、計算欄位、警報規則和通知。只要描述您的需求,其餘交給我。", "new-chat": "新對話", - "no-chats": "尚無對話", "today": "今天", "yesterday": "昨天", "last-7-days": "最近 7 天", @@ -11487,20 +11447,12 @@ "delete-chat-title": "確定要刪除「{{name}}」嗎?", "delete-chat-text": "所有對話訊息都將遺失。", "delete-chat-confirm": "是,刪除", - "action-approval-required": "需要核准此操作", "approve": "核准", "deny": "拒絕", - "processing": "處理中…", "approved": "完成", - "denied": "已拒絕", "error": "失敗", "thinking": "思考中…", - "rename-chat-title": "重新命名此對話", - "main-title": "您好!我是您的 AI 助理", - "approve-all": "核准後續所有操作", - "export-chat": "匯出對話", - "connection-lost": "與 AI 助理的連線已中斷。正在重新連線…", - "reconnect-failed": "無法重新連線至 AI 助理。請重新開啟對話以查看其回覆。" + "export-chat": "匯出對話" }, "converter": { "converter": "資料轉換器", @@ -13202,47 +13154,20 @@ "generate-report-canceled": "已取消產生報表" }, "solution-creator": { - "ai-solution-creator": "AI 解決方案建立工具", "describe-solution-you-want": "描述您想建立的解決方案", - "enter-your-prompt": "輸入您的提示詞", "target": "目標", "install-solution": "安裝", - "solution-overview": "解決方案概觀:{{ name }}", - "dashboards-overview": "儀表板概觀:{{ name }}", - "entity-profile": "實體設定檔", - "entity-profiles": "實體設定檔", - "name": "名稱", - "iam": "IAM", - "iam-full": "身分識別與存取管理", - "table-view": "表格", - "schema-view": "結構圖", - "iam-info": "IAM 資訊", "operation": { "C": "建立", "R": "讀取", "U": "更新", "D": "刪除" }, - "alarm-info": "警報資訊", "description": "說明", - "data": "資料", - "entity-info": "實體資訊", - "calculated-field-info": "計算欄位資訊", - "field-type": "欄位類型", - "scope": "範圍", "delete-alarm-title": "要刪除此建議的警報嗎?", "delete-alarm-text": "此警報是依據您的描述所提出的建議,刪除後將不會納入建議的解決方案。
    您隨時可以在之後手動編輯或重新建立警報。此操作無法復原。", - "basic-mode": "基本", - "advanced-mode": "進階", "create-solution": "建立解決方案", "go-dashboard-manager": "下一步:設計儀表板", - "success-generate-title": "解決方案已就緒!", - "success-generate-sub-title": "按一下下方按鈕,即可將解決方案安裝至您的帳戶", - "success-generate-install-title": "解決方案已安裝!", - "success-generate-install-sub-title": "若要編輯解決方案,請先解除安裝現有執行個體", - "main-title": "您好!我是您的 AI 助理", - "sub-title": "我可以協助您將需求轉換為功能完整的 IoT 解決方案。\n只要描述您想達成的目標,剩下的交給我處理。", - "solutions": "解決方案", "new-solution": "新解決方案", "uninstall-solution": "解除安裝", "uninstall-solution-dialog-title": "確定要解除安裝「{{ name }}」嗎?", @@ -13252,12 +13177,8 @@ "delete-solution-text": "您的所有資料都將遺失", "delete-solution-confirm": "是,刪除", "copy-solution": "複製解決方案", - "expand-sidebar": "展開側邊欄", - "collapse-sidebar": "摺疊側邊欄", "solution-id": "解決方案識別碼", "solution-id-required": "解決方案識別碼為必填項", - "rename-solution-title": "重新命名此解決方案", - "generate-again": "重新產生", "skip-interview": "略過需求訪談", "update-solution": "更新解決方案", "finish-edit": "完成編輯", @@ -13267,8 +13188,6 @@ "water-metering": "用水計量", "coffee-machine-monitoring": "咖啡機監測", "fleet-geofencing": "車隊地理圍欄", - "more-examples": "更多範例", - "hide": "隱藏", "solution-info": "解決方案資訊", "solution-info-with-name": "解決方案資訊:{{ name }}", "status": "狀態", @@ -13281,14 +13200,8 @@ "info": "資訊", "main-dashboard": "主要儀表板", "view-as": "以「{{ name }}」的身分檢視", - "generated-by-calculated-field-name": "由計算欄位「{{ name }}」產生", "estimate-wait-time": "預計等待時間約為 {{ time }}", - "analyzing-your-request": "正在分析您的請求…", "condition": "條件", - "installing": "正在安裝解決方案…", - "step-architecture-design": "架構設計", - "step-dashboard-design": "儀表板設計", - "step-solution-installation": "解決方案安裝", "step-reading-device-data": "正在讀取裝置資料…", "step-analyzing-telemetry-attributes": "正在分析遙測與屬性…", "step-selecting-widgets": "正在為您的資料選擇小工具…", @@ -13320,11 +13233,7 @@ "step-loading-building-alarm-rules": "正在建立警報規則…", "step-loading-assembling-dashboards": "正在組合儀表板…", "step-loading-preparing-states": "正在準備狀態…", - "step-loading-initializing-solution": "正在初始化解決方案…", - "ai-credits": "AI 點數", - "ai-credits-update": "更新方案", - "ai-credits-usage": "AI 點數:已使用 {{ used }},共 {{ max }}", - "ai-credits-description": "本月 AI 點數總額為 {{ max }},已使用 {{ used }}。額度將於 {{ date }} 重設。若要提高 AI 點數額度,請聯絡系統管理員。" + "step-loading-initializing-solution": "正在初始化解決方案…" }, "setup": { "activate-platform": "啟用 ThingsBoard", diff --git a/ui-ngx/src/assets/solution-creator/iot-assistant.svg b/ui-ngx/src/assets/solution-creator/iot-assistant.svg deleted file mode 100644 index 2e473adefa..0000000000 --- a/ui-ngx/src/assets/solution-creator/iot-assistant.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/ui-ngx/src/assets/solution-creator/success.svg b/ui-ngx/src/assets/solution-creator/success.svg deleted file mode 100644 index 58b757228b..0000000000 --- a/ui-ngx/src/assets/solution-creator/success.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/ui-ngx/src/scss/roboto.scss b/ui-ngx/src/scss/roboto.scss index 1c9654f956..48806a35f9 100644 --- a/ui-ngx/src/scss/roboto.scss +++ b/ui-ngx/src/scss/roboto.scss @@ -1,5 +1,9 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +// The @font-face rules of @fontsource-variable/roboto (index.css, wght-italic.css) and +// @fontsource-variable/roboto-mono (index.css, wght-italic.css), copied with the families renamed from 'Roboto Variable' +// and 'Roboto Mono Variable' to 'Roboto' and 'Roboto Mono' and the file URLs pointed at node_modules. +// After upgrading either package, copy those rules again the same way. @font-face { font-family: 'Roboto'; font-style: normal; diff --git a/ui-ngx/src/theme/_app-theme-palette.scss b/ui-ngx/src/theme/_app-theme-palette.scss new file mode 100644 index 0000000000..7e3383e16a --- /dev/null +++ b/ui-ngx/src/theme/_app-theme-palette.scss @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '@angular/material' as mat; +@use '@angular/material/core/tokens/m2-utils'; +@import './theme-constants'; + +$tb-primary: mat.m2-define-palette($mat-tb-primary); +$tb-accent: mat.m2-define-palette($mat-tb-accent); + +$tb-mat-theme: mat.m2-define-light-theme(( + color: ( + primary: $tb-primary, + accent: $tb-accent + ), + typography: mat.m2-define-typography-config( + $button: mat.m2-define-typography-level(14px, 36px, 500, $letter-spacing: 0.03125em) + ), + density: 0 +)); + +$tb-theme-system: m2-utils.get-system($tb-mat-theme); +$tb-theme-system: map_merge($tb-theme-system, ( background: map_get(mat.$m2-grey-palette, 200) )); +$tb-theme: map_merge($tb-mat-theme, (_mat-system: $tb-theme-system)); diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 916b8a9123..c64c46991e 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -1,9 +1,11 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -// The AI experience's design tokens (Uplink). Every AI component reads these, never a raw value: -// --ai-* the AI's colour and light, --chat-* type, space and touch, --entity-* entity types, -// --hl-* / --tb-code-* the code palette, --k-* the chat's greys and strokes. +// The AI experience's styles (Uplink): its design tokens on :root, then the global rules of the AI components. +// Tokens: --ai-* the AI's colour and light, --chat-* type, space and touch, --entity-* entity types, +// --hl-* / --tb-code-* the code palette, --k-* the chat's greys and strokes. Rules use a token where one exists; +// one-off shades of the design (mostly on dark surfaces) stay literal. +// [data-ai] gives AI surfaces the AI's teal instead of the white-labeled primary palette, as the design specifies. :root { --tb-ink-76: rgba(0, 0, 0, 0.76); @@ -16,14 +18,11 @@ --tb-line-soft: rgba(0, 0, 0, 0.05); --tb-line: rgba(0, 0, 0, 0.12); --tb-surface: #ffffff; - --tb-bg: #eeeeee; - --tb-crit-bg: rgba(209, 39, 48, 0.04); --tb-caution-text: #955400; --tb-ok: #198038; --tb-ok-tint: rgba(25, 128, 56, 0.08); --tb-ok-text: #16702f; - --tb-star: #FAE205; --tb-sev-critical: #D12730; --tb-sev-major: #F35E09; @@ -35,7 +34,6 @@ --tb-sev-warning-text: #7D7003; --tb-soft-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 4px rgba(16, 24, 40, 0.04); - --tb-hover-shadow: 0px 4px 10px rgba(23, 33, 90, 0.08); --tb-tile-radius: 10px; --tb-font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; @@ -70,11 +68,6 @@ --ai-w-amber: 55%; --ai-light-stops: var(--ai-light-teal), var(--ai-light-aqua), var(--ai-light-lilac), var(--ai-light-peach), var(--ai-light-amber), var(--ai-light-mint), var(--ai-light-teal); --ai-glow: conic-gradient(in oklab, var(--ai-light-stops)); - --ai-icon: - radial-gradient(80% 80% at 16% 10%, oklch(0.99 0.01 calc(var(--ai-hue) + 5) / 0.6), transparent 62%), - radial-gradient(55% 55% at 0% 100%, color-mix(in oklab, var(--ai-light-mint) 50%, transparent), transparent 70%), - radial-gradient(55% 55% at 100% 0%, color-mix(in oklab, var(--ai-light-amber) 35%, transparent), transparent 70%), - linear-gradient(135deg in oklab, oklch(0.89 0.065 calc(var(--ai-hue) - 8)) 0%, oklch(0.92 0.05 calc(var(--ai-hue) + 25)) 36%, oklch(0.89 0.045 295) 68%, oklch(0.93 0.039 50) 100%); --ai-field-tile: radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) var(--ai-w-teal), transparent), transparent 70%), radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) var(--ai-w-aqua), transparent), transparent 70%), @@ -91,14 +84,6 @@ radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .87), transparent), transparent 70%), radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .87), transparent), transparent 70%), var(--ai-light-paper); - --ai-field-hint: - radial-gradient(60% 75% at 6% 8%, color-mix(in oklab, var(--ai-light-teal) calc(var(--ai-w-teal) * .48), transparent), transparent 70%), - radial-gradient(55% 65% at 70% 0%, color-mix(in oklab, var(--ai-light-aqua) calc(var(--ai-w-aqua) * .48), transparent), transparent 70%), - radial-gradient(50% 60% at 4% 100%, color-mix(in oklab, var(--ai-light-mint) calc(var(--ai-w-mint) * .48), transparent), transparent 70%), - radial-gradient(50% 60% at 62% 62%, color-mix(in oklab, var(--ai-light-lilac) calc(var(--ai-w-lilac) * .48), transparent), transparent 72%), - radial-gradient(45% 60% at 100% 100%, color-mix(in oklab, var(--ai-light-peach) calc(var(--ai-w-peach) * .48), transparent), transparent 70%), - radial-gradient(40% 50% at 100% 40%, color-mix(in oklab, var(--ai-light-amber) calc(var(--ai-w-amber) * .48), transparent), transparent 70%), - var(--ai-light-paper); --chat-text: 16px; --chat-text-lh: 24px; @@ -142,7 +127,6 @@ --ai-deep-pressed: #002624; --ai-action: var(--ai-deep); --ai-action-hover: var(--ai-deep-hover); - --ai-action-pressed: var(--ai-deep-pressed); --ai-on-action: #ffffff; --ai-mark-ink-dark: var(--ai-teal-100); --ai-focus: var(--ai-teal-600); @@ -151,7 +135,6 @@ --ai-selected-text: var(--ai-teal-900); --ai-link: var(--ai-teal-500); --ai-link-strong: var(--ai-teal-900); - --ai-link-line: color-mix(in srgb, var(--ai-teal-500) 35%, transparent); --ai-focus-shadow: color-mix(in srgb, var(--ai-teal-500) 12%, transparent); --ai-dark: #24323b; --ai-on-dark: #e6ebee; @@ -191,7 +174,6 @@ --hl-fn: #d7e8a3; --hl-bool: #f3b6d2; --hl-lvl: #9bdda8; - --hl-mark: rgba(255, 255, 255, 0.6); --k-grey: var(--tb-ink-76); --k-faint: var(--tb-text-muted); @@ -199,42 +181,11 @@ --k-stroke-hover: rgba(0, 0, 0, 0.2); } -[data-type="compact"] { - --chat-text: 14px; - --chat-text-lh: 20px; - --chat-head: 14px; - --chat-head-lh: 20px; - --chat-chip: 14px; - --chat-chip-lh: 18px; - --chat-chip-pad: 0px; - --chat-chip-mono: 13px; - --chat-code-lh: 18px; - --chat-title: 20px; - --chat-title-lh: 28px; -} - -[data-space="compact"] { - --chat-turn-gap: 20px; - --chat-card-pad: 12px; - --chat-icon: 18px; - --chat-mark: 24px; - --chat-control: 28px; -} - -[data-touch] { - --chat-tap: 44px; -} - :root { --chat-read: 760px; --chat-read-log: 712px; --chat-col-min: 340px; --chat-col-max: 800px; - --chat-dock: 364px; - --chat-dock-min: 320px; - --chat-dock-max: 480px; - --chat-split-max: 880px; - --chat-page-min: 560px; } .ai-chat-col, .sol-chat { @@ -703,7 +654,7 @@ min-width: 72px; } - .tb-state { + .tb-ai-state { flex: none; } } @@ -801,7 +752,7 @@ text-overflow: ellipsis; } -.tb-state { +.tb-ai-state { display: inline-flex; align-items: center; gap: 6px; @@ -825,7 +776,7 @@ } } -.tb-rec .tb-state { +.tb-rec .tb-ai-state { height: 20px; gap: 5px; padding: 0 8px 0 7px; @@ -846,9 +797,65 @@ color: var(--tb-ink-76); background: rgba(0, 0, 0, 0.06); } + + &.warn, &.wait { + color: var(--tb-caution-text); + background: color-mix(in srgb, var(--tb-caution) 11%, transparent); + } + + &.wait i { + animation: tb-wait-pulse 1.6s ease-in-out infinite; + } + + &.hub { + padding-left: 6px; + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + + .mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + color: var(--tb-ink-54); + } + } + + &.sev { + padding-left: 6px; + color: var(--sv-t); + background: color-mix(in srgb, var(--sv) 10%, transparent); + + &.critical { --sv: var(--tb-sev-critical); --sv-t: var(--tb-sev-critical); } + &.major { --sv: var(--tb-sev-major); --sv-t: var(--tb-sev-major-text); } + &.minor { --sv: var(--tb-sev-minor); --sv-t: var(--tb-sev-minor-text); } + &.warning { --sv: var(--tb-sev-warning); --sv-t: var(--tb-sev-warning-text); } + &.indeterminate { --sv: var(--tb-sev-indeterminate); --sv-t: var(--tb-ink-76); } + + &.cleared { + color: var(--tb-ink-76); + background: rgba(0, 0, 0, 0.06); + + .tb-sev-mark { + --m: var(--tb-ink-38); + + .r, .d { + stroke: var(--tb-ink-38); + } + } + } + } + + .tb-ack-ic { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + margin: 0 -2px 0 -1px; + } } -.tb-facts { +.tb-ai-facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); align-items: baseline; @@ -868,7 +875,7 @@ } } -.tb-more { +.tb-ai-more { display: inline-flex; align-items: center; gap: 4px; @@ -1114,7 +1121,7 @@ } } - :is(.tb-open, .tb-open-btn, .tb-rec-act, .tb-state.hub) { + :is(.tb-open, .tb-open-btn, .tb-rec-act, .tb-ai-state.hub) { position: relative; z-index: 1; } @@ -1181,6 +1188,106 @@ justify-content: center; } } + + .tb-rec-pic { + &.sq { + width: 80px; + background: #fff; + + img { + object-fit: contain; + padding: 4px; + box-sizing: border-box; + } + } + + &.wide { + width: 160px; + } + } + + &.with-pic.with-details .tb-rec-pic { + border-bottom-left-radius: 0; + } + + .tb-open { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--tb-ink-54); + text-decoration: none; + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } + } + + .tb-rec-det { + display: grid; + gap: 8px; + margin: 10px -12px -12px; + padding: 10px 12px 12px; + border-top: 1px solid var(--tb-line); + border-radius: 0 0 11px 11px; + background: rgba(16, 24, 40, 0.03); + + > .k-chips { + margin: 2px 0 0; + } + } + + .tb-rec-note { + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + .tb-ai-facts code { + padding: 1px 5px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: .92em; + } + + .tb-rec-meta .tight-only { + display: none; + } + + .tb-rec-side { + min-width: 0; + } + + &.tight { + .tb-rec-meta .tight-only { + display: inline-flex; + } + + .tb-rec-side > .tb-ai-state.hub { + display: none; + } + + &.primary:not(.open-icon) .tb-open-btn { + flex: 1 1 auto; + width: auto; + } + } } .k-time { @@ -1271,7 +1378,7 @@ line-height: var(--chat-meta-lh); } - > .tb-state { + > .tb-ai-state { grid-column: 3; grid-row: 1 / span 2; } @@ -1500,27 +1607,21 @@ .mat-mdc-unelevated-button:not(:disabled) { --mat-button-filled-container-color: var(--ai-action); --mat-button-filled-label-text-color: var(--ai-on-action); - --mdc-filled-button-container-color: var(--ai-action); - --mdc-filled-button-label-text-color: var(--ai-on-action); padding: 0 16px; } .mat-mdc-unelevated-button.warn:not(:disabled) { --mat-button-filled-container-color: var(--tb-crit); - --mdc-filled-button-container-color: var(--tb-crit); } .mat-mdc-button:not(:disabled) { --mat-button-text-label-text-color: var(--tb-ink-76); - --mdc-text-button-label-text-color: var(--tb-ink-76); padding: 0 8px; } .mat-mdc-outlined-button:not(:disabled) { --mat-button-outlined-label-text-color: var(--tb-ink-76); - --mdc-outlined-button-label-text-color: var(--tb-ink-76); --mat-button-outlined-outline-color: var(--k-stroke); - --mdc-outlined-button-outline-color: var(--k-stroke); background: var(--tb-surface); } @@ -2972,6 +3073,19 @@ a.tb-chiplink:focus-visible { border-radius: 0; background: none; } + + > .tb-rec.line { + width: fit-content; + max-width: 100%; + + .tb-rec-tile { + background: none; + } + + + .tb-rec.line { + border-top: 1px solid rgba(0, 0, 0, 0.06); + } + } } .art-ib { @@ -3027,6 +3141,8 @@ a.tb-chiplink:focus-visible { @media (prefers-reduced-motion: reduce) { animation: none; } + + --art-bg: var(--tb-surface); } @keyframes art-pane-in { @@ -3070,7 +3186,6 @@ a.tb-chiplink:focus-visible { } } - .art-pane-head { position: relative; z-index: 3; @@ -3093,7 +3208,6 @@ a.tb-chiplink:focus-visible { } } - .art-pane-body { flex: 1; min-height: 0; @@ -3132,7 +3246,6 @@ a.tb-chiplink:focus-visible { background: var(--tb-surface); } - .art-tray { position: absolute; left: 50%; @@ -3232,7 +3345,6 @@ a.tb-chiplink:focus-visible { background: var(--tb-caution); } - @media (max-width: 1099px) { .art-cols.with-pane { position: relative; @@ -3263,7 +3375,6 @@ a.tb-chiplink:focus-visible { } } - .art-pane-head::after, .art-pane-foot::before { content: ''; position: absolute; @@ -3336,10 +3447,6 @@ a.tb-chiplink:focus-visible { } } -.art-pane { - --art-bg: var(--tb-surface); -} - .art-pane.art-dark { --art-bg: var(--tb-code-bg); --k-grey: var(--tb-code-head-fg); @@ -3394,32 +3501,6 @@ a.tb-chiplink:focus-visible { .art-pane-body { scrollbar-color: rgba(255, 255, 255, 0.22) transparent; } - - .art-edit { - color: rgba(255, 255, 255, 0.72); - - &:hover { - background: rgba(255, 255, 255, 0.08); - color: #fff; - } - - &[aria-checked="true"] { - color: #fff; - - .art-edit-sw { - background: var(--ai-light-mint); - - i { - background: #1d2830; - box-shadow: none; - } - } - } - } - - .art-edit-sw { - background: rgba(255, 255, 255, 0.24); - } } .art-pane-head h2.art-title { @@ -3532,23 +3613,32 @@ a.tb-chiplink:focus-visible { } } -.art-edit { - display: inline-flex; - align-items: center; +.art-cards { + display: grid; gap: 8px; - height: 32px; - padding: 0 8px 0 10px; - border: 0; - border-radius: 16px; - background: none; - font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); - color: var(--tb-ink-76); + max-width: 480px; +} + +.art-card { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + padding: 8px 10px 8px 12px; + border: 1px solid var(--k-stroke); + border-radius: 10px; + background: var(--tb-surface); + font: inherit; + font-size: 14px; + line-height: 20px; + text-align: left; + color: var(--tb-ink); cursor: pointer; - transition: background-color .15s ease, color .15s ease; + transition: border-color .15s ease, background-color .15s ease; &:hover { - background: color-mix(in srgb, var(--tb-ink) 5%, transparent); - color: var(--tb-ink); + border-color: var(--k-stroke-hover, rgba(0, 0, 0, 0.2)); + background: color-mix(in srgb, var(--tb-ink) 2%, transparent); } &:focus-visible { @@ -3556,102 +3646,17 @@ a.tb-chiplink:focus-visible { outline-offset: 1px; } - > .mat-icon { - width: 18px; - height: 18px; - font-size: 18px; - } - - &[aria-checked="true"] { - color: var(--tb-ink); + &.on { + border-color: color-mix(in srgb, var(--ai-action) 45%, var(--k-stroke)); + background: var(--ai-selected-wash); - .art-edit-sw { + .art-card-ic { background: var(--ai-action); + color: var(--ai-on-action); + } - i { - transform: translateX(12px); - } - } - } -} - -.art-edit-sw { - position: relative; - flex: none; - width: 28px; - height: 16px; - border-radius: 8px; - background: color-mix(in srgb, var(--tb-ink) 22%, transparent); - transition: background-color .18s ease; - - i { - position: absolute; - top: 2px; - left: 2px; - width: 12px; - height: 12px; - border-radius: 50%; - background: #fff; - box-shadow: 0 1px 2px rgba(16, 24, 40, 0.25); - transition: transform .18s cubic-bezier(.2, 0, 0, 1); - } -} - -@container pane (max-width: 520px) { - .art-edit-t { - display: none; - } - - .art-edit { - gap: 6px; - padding: 0 6px 0 8px; - } -} - -.art-cards { - display: grid; - gap: 8px; - max-width: 480px; -} - -.art-card { - display: flex; - align-items: center; - gap: 12px; - width: 100%; - padding: 8px 10px 8px 12px; - border: 1px solid var(--k-stroke); - border-radius: 10px; - background: var(--tb-surface); - font: inherit; - font-size: 14px; - line-height: 20px; - text-align: left; - color: var(--tb-ink); - cursor: pointer; - transition: border-color .15s ease, background-color .15s ease; - - &:hover { - border-color: var(--k-stroke-hover, rgba(0, 0, 0, 0.2)); - background: color-mix(in srgb, var(--tb-ink) 2%, transparent); - } - - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 1px; - } - - &.on { - border-color: color-mix(in srgb, var(--ai-action) 45%, var(--k-stroke)); - background: var(--ai-selected-wash); - - .art-card-ic { - background: var(--ai-action); - color: var(--ai-on-action); - } - - .mat-icon.art-card-chev { - color: var(--ai-action); + .mat-icon.art-card-chev { + color: var(--ai-action); } } } @@ -3744,6 +3749,14 @@ cursor: pointer; line-height: var(--chat-caption-lh); color: var(--k-grey); } + + small { + font-variant-numeric: tabular-nums; + } + + b .art-name { + display: block; + } } .art-card .mat-icon.art-card-chev { @@ -3774,7 +3787,6 @@ cursor: pointer; --hl-fn: #3f6212; --hl-bool: #a21caf; --hl-lvl: #15803d; - --hl-mark: rgba(0, 0, 0, 0.5); flex: 1; min-height: 0; overflow: auto; @@ -3785,6 +3797,50 @@ cursor: pointer; letter-spacing: .25px; color: var(--fc-ink); tab-size: 2; + + .hl-cmd, .hl-ok { + color: var(--hl-cmd); + } + + .hl-flag { + color: var(--hl-flag); + } + + .hl-str, .hl-warn { + color: var(--hl-str); + } + + .hl-num, .hl-kw { + color: var(--hl-num); + } + + .hl-key, .hl-var { + color: var(--hl-key); + } + + .hl-com, .hl-op { + color: var(--hl-com); + } + + .hl-err { + color: var(--hl-err); + } + + .hl-val { + color: var(--fc-ink); + } + + .hl-fn { + color: var(--hl-fn); + } + + .hl-bool { + color: var(--hl-bool); + } + + .hl-lvl { + color: var(--hl-lvl); + } } .art-dark :is(.file-code, .file-edit) { @@ -3802,7 +3858,6 @@ cursor: pointer; --hl-fn: #d7e8a3; --hl-bool: #f3b6d2; --hl-lvl: #9bdda8; - --hl-mark: rgba(255, 255, 255, 0.6); } .file-lines { @@ -3856,6 +3911,32 @@ cursor: pointer; .tb-line { display: inline; } + + .ln { + border: 0; + font: inherit; + cursor: pointer; + } + + li.marked, li.marked .ln { + background: color-mix(in srgb, var(--fc-mark), var(--art-bg)); + } + + li.marked .ln { + color: var(--fc-mark-ink); + box-shadow: inset -2px 0 0 var(--fc-mark-ink); + } + + mark.fm { + border-radius: 2px; + background: var(--fc-find); + color: inherit; + + &.now { + background: var(--fc-find-now); + box-shadow: 0 0 0 1px var(--fc-find-now); + } + } } .file-code.wrap .file-lines { @@ -3915,55 +3996,7 @@ cursor: pointer; li + li { margin-top: 4px; } -} - -.file-code, .file-edit { - .hl-cmd, .hl-ok { - color: var(--hl-cmd); - } - - .hl-flag { - color: var(--hl-flag); - } - - .hl-str, .hl-warn { - color: var(--hl-str); - } - - .hl-num, .hl-kw { - color: var(--hl-num); - } - - .hl-key, .hl-var { - color: var(--hl-key); - } - .hl-com, .hl-op { - color: var(--hl-com); - } - - .hl-err { - color: var(--hl-err); - } - - .hl-val { - color: var(--fc-ink); - } - - .hl-fn { - color: var(--hl-fn); - } - - .hl-bool { - color: var(--hl-bool); - } - - .hl-lvl { - color: var(--hl-lvl); - } -} - -.file-md { pre { margin: 0 0 16px; padding: 12px 16px; @@ -4014,8 +4047,7 @@ cursor: pointer; } .agent.streaming [class*="tb-markdown-view"] > :is(p, h1, h2, h3, h4, h5, h6):last-child::after, -.agent.streaming [class*="tb-markdown-view"] > :is(ul, ol):last-child > li:last-child::after, -.k-caret { +.agent.streaming [class*="tb-markdown-view"] > :is(ul, ol):last-child > li:last-child::after { content: ''; display: inline-block; width: 2px; @@ -4138,34 +4170,6 @@ cursor: pointer; --fc-find-now: rgba(250, 204, 21, 0.55); } -.file-lines { - .ln { - border: 0; - font: inherit; - cursor: pointer; - } - - li.marked, li.marked .ln { - background: color-mix(in srgb, var(--fc-mark), var(--art-bg)); - } - - li.marked .ln { - color: var(--fc-mark-ink); - box-shadow: inset -2px 0 0 var(--fc-mark-ink); - } - - mark.fm { - border-radius: 2px; - background: var(--fc-find); - color: inherit; - - &.now { - background: var(--fc-find-now); - box-shadow: 0 0 0 1px var(--fc-find-now); - } - } -} - .file-code.ws .ws { position: relative; @@ -4197,10 +4201,11 @@ cursor: pointer; display: flex; align-items: center; gap: 6px; - height: 40px; + height: 48px; padding: 0 8px 0 12px; border-bottom: 1px solid var(--k-stroke); background: var(--art-bg); + box-sizing: border-box; } .art-dark .file-find { @@ -4233,14 +4238,6 @@ cursor: pointer; } } -.file-find-n { - flex: none; - white-space: nowrap; - font-size: var(--chat-caption); - line-height: var(--chat-caption-lh); - color: var(--k-grey); -} - .file-find-b { flex: none; display: inline-flex; @@ -4278,6 +4275,31 @@ cursor: pointer; background: rgba(255, 255, 255, 0.08); color: #fff; } + + .file-bar-info { + color: var(--tb-code-head-fg); + } + + .file-bar-sep { + color: rgba(255, 255, 255, 0.28); + } + + .file-bar-state { + color: var(--tb-code-fg); + } + + :is(.file-bar-saved, .file-bar-ed) { + color: var(--ai-dark-accent); + } + + .file-bar-acts .mdc-button.file-bar-save:not(:disabled) { + background: var(--ai-dark-accent); + color: var(--tb-code-bg); + + &:hover { + background: var(--ai-dark-accent-hover); + } + } } .art-spacer { @@ -4299,6 +4321,10 @@ cursor: pointer; .art-pane-foot .file-marked { white-space: nowrap; + + gap: 8px; + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--k-grey); } .art-dark .art-pane-foot .mdc-button.mat-mdc-outlined-button { @@ -4325,18 +4351,13 @@ cursor: pointer; } .mdc-button:not(.mat-mdc-unelevated-button) { - --mdc-text-button-label-text-color: var(--tb-code-fg); --mat-button-text-label-text-color: var(--tb-code-fg); - --mdc-outlined-button-label-text-color: var(--tb-code-fg); --mat-button-outlined-label-text-color: var(--tb-code-fg); - --mdc-outlined-button-outline-color: rgba(255, 255, 255, 0.24); --mat-button-outlined-outline-color: rgba(255, 255, 255, 0.24); } .art-ask { - --mdc-filled-button-container-color: var(--ai-dark-accent); --mat-button-filled-container-color: var(--ai-dark-accent); - --mdc-filled-button-label-text-color: var(--tb-code-bg); --mat-button-filled-label-text-color: var(--tb-code-bg); } } @@ -5103,11 +5124,6 @@ tb-ai-action-detail.k-detail { &.on { background: var(--ai-selected-wash); } - - .k-spin { - --spin: 20px; - flex: none; - } } .art-list-ic { @@ -5302,16 +5318,6 @@ tb-ai-action-detail.k-detail { display: block; } -.art-card-t { - small { - font-variant-numeric: tabular-nums; - } - - b .art-name { - display: block; - } -} - .art-card-ed { margin-left: 6px; font-weight: 500; @@ -5460,33 +5466,6 @@ tb-ai-action-detail.k-detail { } } -.art-dark { - .file-bar-info { - color: var(--tb-code-head-fg); - } - - .file-bar-sep { - color: rgba(255, 255, 255, 0.28); - } - - .file-bar-state { - color: var(--tb-code-fg); - } - - :is(.file-bar-saved, .file-bar-ed) { - color: var(--ai-dark-accent); - } - - .file-bar-acts .mdc-button.file-bar-save:not(:disabled) { - background: var(--ai-dark-accent); - color: var(--tb-code-bg); - - &:hover { - background: var(--ai-dark-accent-hover); - } - } -} - @container pane (max-width: 470px) { .file-bar :is(.file-bar-pos, .file-bar-sep:has(+ .file-bar-pos)) { display: none; @@ -5655,12 +5634,12 @@ tb-ai-action-detail.k-detail { } } -.file-find { - height: 48px; - box-sizing: border-box; -} - .file-find-n { + flex: none; + white-space: nowrap; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-grey); display: inline-flex; align-items: center; gap: 3px; @@ -5706,13 +5685,7 @@ tb-ai-action-detail.k-detail { width: 1px; height: 18px; margin: 0 4px; - background: var(--fc-rule, var(--k-stroke)); -} - -.art-pane-foot .file-marked { - gap: 8px; - font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); - color: var(--k-grey); + background: var(--k-stroke); } .file-marked-n { @@ -6023,154 +5996,17 @@ tb-ai-action-detail.k-detail { } } -.tb-rec .tb-state { - &.warn, &.wait { - color: var(--tb-caution-text); - background: color-mix(in srgb, var(--tb-caution) 11%, transparent); - } - - &.wait i { - animation: tb-wait-pulse 1.6s ease-in-out infinite; - } - - &.hub { - padding-left: 6px; - color: var(--tb-ink-76); - background: rgba(0, 0, 0, 0.06); - - .mat-icon { - font-size: 14px; - width: 14px; - height: 14px; - line-height: 14px; - color: var(--tb-ink-54); - } - } - - &.sev { - padding-left: 6px; - color: var(--sv-t); - background: color-mix(in srgb, var(--sv) 10%, transparent); - - &.critical { --sv: var(--tb-sev-critical); --sv-t: var(--tb-sev-critical); } - &.major { --sv: var(--tb-sev-major); --sv-t: var(--tb-sev-major-text); } - &.minor { --sv: var(--tb-sev-minor); --sv-t: var(--tb-sev-minor-text); } - &.warning { --sv: var(--tb-sev-warning); --sv-t: var(--tb-sev-warning-text); } - &.indeterminate { --sv: var(--tb-sev-indeterminate); --sv-t: var(--tb-ink-76); } - - &.cleared { - color: var(--tb-ink-76); - background: rgba(0, 0, 0, 0.06); - - .tb-sev-mark { - --m: var(--tb-ink-38); - - .r, .d { - stroke: var(--tb-ink-38); - } - } - } - } - - .tb-ack-ic { - font-size: 14px; - width: 14px; - height: 14px; - line-height: 14px; - margin: 0 -2px 0 -1px; - } -} - @keyframes tb-wait-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.7); } } @media (prefers-reduced-motion: reduce) { - .tb-rec .tb-state.wait i { + .tb-rec .tb-ai-state.wait i { animation: none; } } -.tb-rec.card { - .tb-rec-pic { - &.sq { - width: 80px; - background: #fff; - - img { - object-fit: contain; - padding: 4px; - box-sizing: border-box; - } - } - - &.wide { - width: 160px; - } - } - - &.with-pic.with-details .tb-rec-pic { - border-bottom-left-radius: 0; - } - - .tb-open { - position: relative; - flex: none; - display: inline-flex; - align-items: center; - justify-content: center; - width: 28px; - height: 28px; - padding: 0; - border: 0; - border-radius: 50%; - background: none; - color: var(--tb-ink-54); - text-decoration: none; - cursor: pointer; - - &:hover { - background: rgba(0, 0, 0, 0.06); - color: var(--tb-ink); - } - - &:focus-visible { - outline: 2px solid var(--tb-primary-300); - outline-offset: 1px; - } - } - - .tb-rec-det { - display: grid; - gap: 8px; - margin: 10px -12px -12px; - padding: 10px 12px 12px; - border-top: 1px solid var(--tb-line); - border-radius: 0 0 11px 11px; - background: rgba(16, 24, 40, 0.03); - - > .k-chips { - margin: 2px 0 0; - } - } - - .tb-rec-note { - margin: 0; - font-size: var(--chat-line); - line-height: var(--chat-line-lh); - color: var(--tb-ink-76); - } - - .tb-facts code { - padding: 1px 5px; - border-radius: 4px; - background: rgba(0, 0, 0, 0.06); - font-family: var(--tb-mono); - font-size: .92em; - } -} - .tb-list-head.static { cursor: default; } @@ -6241,7 +6077,7 @@ tb-ai-record-card { } @container k-chat (max-width: 420px) { - .tb-facts { + .tb-ai-facts { grid-template-columns: minmax(0, 1fr); gap: 0; @@ -6256,7 +6092,7 @@ tb-ai-record-card { } @container pane (max-width: 470px) { - .tb-facts { + .tb-ai-facts { grid-template-columns: minmax(0, 1fr); gap: 0; @@ -6274,31 +6110,6 @@ tb-ai-record-card { margin-right: 12px; } -.tb-rec.card { - .tb-rec-meta .tight-only { - display: none; - } - - .tb-rec-side { - min-width: 0; - } - - &.tight { - .tb-rec-meta .tight-only { - display: inline-flex; - } - - .tb-rec-side > .tb-state.hub { - display: none; - } - - &.primary:not(.open-icon) .tb-open-btn { - flex: 1 1 auto; - width: auto; - } - } -} - tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { width: auto; max-height: none; @@ -6306,7 +6117,7 @@ tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { padding-right: 0; margin-left: 24px; - > .tb-more { + > .tb-ai-more { justify-self: start; } @@ -6390,7 +6201,7 @@ tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { margin: -4px -4px 0 4px; } - .tb-state { + .tb-ai-state { grid-column: 2 / -1; grid-row: 2; justify-self: start; @@ -6431,7 +6242,7 @@ tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { min-width: 0; } - > .tb-state { + > .tb-ai-state { grid-column: 3; grid-row: 1; } @@ -6459,21 +6270,6 @@ tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) { } } -.tb-list-body { - > .tb-rec.line { - width: fit-content; - max-width: 100%; - - .tb-rec-tile { - background: none; - } - - + .tb-rec.line { - border-top: 1px solid rgba(0, 0, 0, 0.06); - } - } -} - tb-ai-action-detail.k-detail .k-detail-recs:is(.k-detail-hub, .k-detail-list) ~ .k-detail-more { margin-left: 24px; } diff --git a/ui-ngx/src/theme/app-theme.scss b/ui-ngx/src/theme/app-theme.scss index 4b2231b2ce..5da9183aeb 100644 --- a/ui-ngx/src/theme/app-theme.scss +++ b/ui-ngx/src/theme/app-theme.scss @@ -2,32 +2,13 @@ // SPDX-License-Identifier: BUSL-1.1 @use '@angular/material' as mat; @use './app-theme-overwrites' as overwrites; -@use '@angular/material/core/tokens/m2-utils'; @import './datepicker-theme'; -@import './theme-constants'; +@import './app-theme-palette'; @import './ai-theme'; @include mat.elevation-classes(); @include mat.app-background(); -$tb-primary: mat.m2-define-palette($mat-tb-primary); -$tb-accent: mat.m2-define-palette($mat-tb-accent); - -$tb-mat-theme: mat.m2-define-light-theme(( - color: ( - primary: $tb-primary, - accent: $tb-accent - ), - typography: mat.m2-define-typography-config( - $button: mat.m2-define-typography-level(14px, 36px, 500, $letter-spacing: 0.03125em) - ), - density: 0 -)); - -$tb-theme-system: m2-utils.get-system($tb-mat-theme); -$tb-theme-system: map_merge($tb-theme-system, ( background: map_get(mat.$m2-grey-palette, 200) )); -$tb-theme: map_merge($tb-mat-theme, (_mat-system: $tb-theme-system)); - .tb-default { @include mat.all-component-themes($tb-theme); @include mat-datetimepicker-theme($tb-theme); From f6f982873dc2d073b92a5c16cf70728e5469e141 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Mon, 30 Nov 2026 14:54:33 +0200 Subject: [PATCH 181/183] Ask cards keep the color flag; review values translated by value aiQuestionsOf passes color through (never with multiple), so a color question gets the picker even without hex options. The approval card translates the common review values (on, off, automatic, set, not set, default) whatever the field, with English text unchanged; labels for the new tlsVersion, passwordSecret and proxyPasswordSecret fields. --- .../modules/home/components/ai/ai-action.models.ts | 3 ++- .../components/ai/ai-approval-card.component.ts | 4 ++++ ui-ngx/src/assets/locale/locale.constant-en_US.json | 13 +++++++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index 6b97da9c68..a5e8c87c3d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -526,7 +526,8 @@ export function aiQuestionsOf(args: unknown): AiQuestion[] { .map(option => ({label: option.label.trim(), hint: typeof option.hint === 'string' ? option.hint : undefined})), recommended: Array.isArray(question.recommended) ? question.recommended.filter(label => typeof label === 'string') : undefined, multiple: question.multiple === true, - secret: question.secret === true && !(Array.isArray(question.options) && question.options.length) + secret: question.secret === true && !(Array.isArray(question.options) && question.options.length), + color: question.color === true && question.multiple !== true })); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 585ddd6378..69aabaf19d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -149,6 +149,7 @@ const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLI const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/; const STACK_AT = 24; +const COMMON_VALUES = new Set(['on', 'off', 'automatic', 'set', 'not set', 'default']); const OWN_TYPE_LABELS = new Set(['ALARM_RULE', 'DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER', 'REPORT_COMPONENT', 'REPORT_ENTITY_ALIAS', 'REPORT_FILTER', 'SCHEDULED_REPORT', 'SCADA_SYMBOL']); const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); @@ -467,6 +468,9 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { if (field.id && VALUE_TOKENS[field.id]?.includes(value)) { return this.translate.instant(`ai-assistant.review.value.${field.id}-${value.replace(/ /g, '-')}`); } + if (COMMON_VALUES.has(value)) { + return this.translate.instant(`ai-assistant.review.value.${value.replace(/ /g, '-')}`); + } return value; } 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 f635c9a9f4..886d065747 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -2833,7 +2833,10 @@ "sms": "SMS", "body": "Message", "keys": "Keys", - "scope": "Scope" + "scope": "Scope", + "tlsVersion": "TLS version", + "passwordSecret": "Password from secret storage", + "proxyPasswordSecret": "Proxy password from secret storage" }, "value": { "removeVolumes-yes": "Yes, for good", @@ -2852,7 +2855,13 @@ "defaultDashboard-none": "None: the current one is cleared", "homeDashboard-none": "None: the current one is cleared", "clears-yes": "when its clear condition holds", - "clears-no": "only by hand" + "clears-no": "only by hand", + "on": "on", + "off": "off", + "automatic": "automatic", + "set": "set", + "not-set": "not set", + "default": "Default" }, "detail": { "server-attributes": "server attributes", From 8aaf9ba9134f5de0a662c64a78da0d0c6ee351e6 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Mon, 30 Nov 2026 15:11:48 +0200 Subject: [PATCH 182/183] Composer credits ring turns amber near the limit and the line uses the caution text colour, as in the design --- .../modules/home/components/ai/ai-credits.component.scss | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss index 1f317e3f1c..7fb233ca15 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss @@ -13,7 +13,7 @@ } .cred.near .cred-line { - color: var(--tb-caution); + color: var(--tb-caution-text); } .cred-ring { @@ -56,6 +56,10 @@ } } +.cred.near .arc { + stroke: var(--tb-caution); +} + .cred.over .arc { stroke: var(--tb-crit); } From 41bae059b2f5cf265124c1a65ddcee7309f2345c Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Mon, 30 Nov 2026 15:17:59 +0200 Subject: [PATCH 183/183] Map layer settings: project the API key warning into the field suffix through an ng-container (NG8011) --- .../map-layer-settings-panel.component.html | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html index c37facc148..0ebf2f4deb 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html @@ -137,18 +137,19 @@ @if (apiKeyMissingWarning(); as warning) { - - warning - + + + warning + + }