diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java index d0c29ff1e0..64610ce271 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java @@ -46,6 +46,9 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { private static final Map alarmFieldColumnMap = new HashMap<>(); + private static final String SEVERITY_RANK = "case a." + ModelConstants.ALARM_SEVERITY_PROPERTY + + " when 'CRITICAL' then 0 when 'MAJOR' then 1 when 'MINOR' then 2 when 'WARNING' then 3 when 'INDETERMINATE' then 4 else 5 end"; + private static final Set ALARM_TABLE_SORT_COLUMNS = Set.of(ModelConstants.CREATED_TIME_PROPERTY, ModelConstants.ALARM_ACK_TS_PROPERTY, ModelConstants.ALARM_CLEAR_TS_PROPERTY, ModelConstants.ALARM_ASSIGN_TS_PROPERTY, ModelConstants.ALARM_END_TS_PROPERTY, ModelConstants.ALARM_START_TS_PROPERTY, ModelConstants.ALARM_ACKNOWLEDGED_PROPERTY, ModelConstants.ALARM_CLEARED_PROPERTY, @@ -211,7 +214,8 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { if ("status".equalsIgnoreCase(sortOrderKey)) { selectPart.append(", a.status as status "); } - sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)) + String sortColumn = alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey); + sortPart.append(ModelConstants.ALARM_SEVERITY_PROPERTY.equals(sortColumn) ? SEVERITY_RANK : sortColumn) .append(" ").append(sortOrder.getDirection().name()); if (ownerScoped) { sortPart.append(", a.created_time desc, a.id desc"); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java index e4b49b155b..d0c19ec12c 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java @@ -800,6 +800,42 @@ public class AlarmServiceTest extends AbstractServiceTest { Assert.assertTrue(firstPage.hasNext()); } + @Test + public void testSortAlarmDataBySeverityPriority() { + Device device = new Device(); + device.setName("TestSeverityDevice"); + device.setType("default"); + device.setTenantId(tenantId); + device = deviceService.saveDevice(device); + + long ts = System.currentTimeMillis(); + List ids = new ArrayList<>(); + for (AlarmSeverity severity : List.of(AlarmSeverity.INDETERMINATE, AlarmSeverity.CRITICAL, AlarmSeverity.WARNING, AlarmSeverity.MAJOR, AlarmSeverity.MINOR)) { + ids.add(alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(device.getId()) + .type("Severity " + severity) + .severity(severity) + .startTs(ts).build()).getAlarm().getId()); + } + List byPriority = List.of(ids.get(1), ids.get(3), ids.get(4), ids.get(2), ids.get(0)); + + AlarmDataPageLink pageLink = new AlarmDataPageLink(); + pageLink.setPage(0); + pageLink.setPageSize(10); + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + AlarmDataQuery ownerQuery = new AlarmDataQuery(null, pageLink, null, null, null, Collections.emptyList()); + + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId())) + .getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC)); + Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + } + private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { return toQuery(pageLink, Collections.emptyList()); } 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 645ab4a114..3a91763c7f 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -50,10 +50,6 @@ export class AiChatService { return this.http.get>(`/api/ai/chats/${chatId}/messages`, defaultHttpOptionsFromConfig(config)) } - public generateDashboard(deviceId: string, timeseriesKeys?: string[], config?: RequestConfig): Observable { - return this.http.post(`/api/ai/devices/${deviceId}/dashboard`, { timeseriesKeys }, defaultHttpOptionsFromConfig(config)); - } - public resolveToolApproval(result: ApprovalResult, config?: RequestConfig): Observable { return this.http.post('/api/ai/tools/resolve-approval', result, defaultHttpOptionsFromConfig(config)) } 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 e0d3028f40..32d2b7fb33 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 @@ -215,6 +215,9 @@ export class AiAssistantPanelService implements OnDestroy { } toggle(): void { + if (this._suppressed() && !this._open()) { + return; + } this._restored.set(false); this._open.update(open => !open); } @@ -317,6 +320,37 @@ export class AiAssistantPanelService implements OnDestroy { } }); + private static readonly STARTED_KEY = 'tb-ai-panel-started'; + private static readonly STARTED_MAX = 20; + + private _startedByContext = signal>(AiAssistantPanelService.readStarted()); + + private static readStarted(): Record { + try { + const stored = JSON.parse(AiAssistantPanelService.readSession(AiAssistantPanelService.STARTED_KEY) ?? '{}'); + return stored && typeof stored === 'object' ? stored : {}; + } catch { + return {}; + } + } + + noteStartedHere(chatId: string): void { + const key = this.contextKey(); + if (!key) { + return; + } + this._startedByContext.update(started => { + const next = {...started, [key]: [chatId, ...(started[key] ?? []).filter(id => id !== chatId)].slice(0, AiAssistantPanelService.STARTED_MAX)}; + AiAssistantPanelService.writeSession(AiAssistantPanelService.STARTED_KEY, JSON.stringify(next)); + return next; + }); + } + + chatsStartedHere(): string[] { + const key = this.contextKey(); + return key ? this._startedByContext()[key] ?? [] : []; + } + setLastChatId(id: string | undefined): void { const key = this.contextKey(); if (!key) { @@ -341,10 +375,34 @@ export class AiAssistantPanelService implements OnDestroy { } openPanel(): void { + if (this._suppressed()) { + return; + } this._restored.set(false); this._open.set(true); } + private _composed = signal<{text: string; fresh: boolean} | null>(null); + readonly composed = this._composed.asReadonly(); + + compose(text: string): void { + if (this._suppressed()) { + return; + } + this._composed.set({text, fresh: !this._open()}); + this.openPanel(); + } + + composesFresh(): boolean { + return !!this._composed()?.fresh; + } + + takeComposed(): {text: string; fresh: boolean} | null { + const composed = this._composed(); + this._composed.set(null); + return composed; + } + setEnabled(enabled: boolean): void { this._enabled.set(enabled); if (enabled) { 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 939c25ddff..d4eb2310ea 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 @@ -142,7 +142,7 @@ } } @if (plainRows(block.rows).length) { -
+
@for (fact of plainRows(block.rows); track $index) {
{{ label(fact) }}
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 0757247883..0180665132 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 @@ -127,7 +127,7 @@ export interface AiStepView { const ASKED_FOR: Record = { 'search-named': 'named', 'search-typed': 'typed', 'search-text': 'text', 'search-related-from': 'related-from', - 'search-related-to': 'related-to', 'search-alarms-of': 'alarms-of', 'read-attributes-scope': 'attributes-scope', + 'search-related-to': 'related-to', 'read-attributes-scope': 'attributes-scope', 'search-alarms': 'alarms', 'search-alarms-on': 'alarms-on', 'search-alarms-filter-on': 'alarms-filter-on', 'search-alarms-window': 'alarms-window', 'search-alarms-filter-window': 'alarms-filter-window', 'search-alarms-on-window': 'alarms-on-window', 'search-alarms-filter-on-window': 'alarms-filter-on-window', 'read-history': 'history', 'read-history-keys': 'history-keys', 'read-latest-keys': 'latest-keys', 'iot-hub-query': 'query', @@ -1295,6 +1295,10 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail }; case 'create_dashboard': return {hood: text('create-dashboard', {name: str(values.title) ?? '—'}), blocks: []}; + case 'generate_device_dashboard': { + const keys = Array.isArray(values.keys) ? values.keys.map(String) : []; + return {hood: text('generate-device-dashboard', {entity: of(values.deviceId, 'DEVICE')}), blocks: keys.length ? [{type: 'keys', keys}] : []}; + } case 'update_dashboard': return {hood: text('update-dashboard', {entity: dashboard}), blocks: changes(values, ['dashboardId'], names)}; case 'read_dashboard_overview': @@ -2360,6 +2364,9 @@ function namesOf(message: {from: string; data?: any; references?: Array<{id: str case 'create_dashboard': put(created, values.title, 'DASHBOARD'); break; + case 'generate_device_dashboard': + put(created, undefined, 'DASHBOARD'); + break; case 'save_device': put(created ?? savedObject(values).id, savedObject(values).name, 'DEVICE'); break; 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 d2afdc3ec3..06f4f75667 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 @@ -40,6 +40,7 @@ const TOOL_WORDS: Record = { test_converter: 'test-converter', read_converter_library: 'read-converter-library', create_dashboard: 'create-dashboard', + generate_device_dashboard: 'generate-device-dashboard', update_dashboard: 'update-dashboard', add_dashboard_state: 'add-dashboard-state', update_dashboard_state: 'update-dashboard-state', 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 5906317f70..b8d19aa09f 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 @@ -55,6 +55,8 @@ const MAX_FIELDS = 5; const DETAIL_TOKENS = new Set(['server-attributes', 'shared-attributes']); +const ATTRIBUTE_TOOLS = new Set(['save_attributes', 'delete_attributes']); + const VALUE_TOKENS: Record = { undo: ['none'], defaultDashboard: ['none'], @@ -72,7 +74,7 @@ const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); const HEAD_VERBS = new Set(['create', 'update', 'delete', 'install', 'acknowledge', 'clear', 'assign', 'unassign']); const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync', 'acknowledge', 'clear', 'assign', 'unassign']); -const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol']); +const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol', 'dashboard-image']); const BLOCK_FIELDS = new Set(['script']); @@ -195,6 +197,11 @@ function aiChangeHead(translate: TranslateService, data: ToolExecutionRequested) if (!HEAD_VERBS.has(verb)) { return translate.instant(label); } + if (DETAIL_TOKENS.has(review.detail) || ATTRIBUTE_TOOLS.has(data.tool)) { + const kind = DETAIL_TOKENS.has(review.detail) ? translate.instant('ai-assistant.review.detail.' + review.detail) + : translate.instant('ai-assistant.review.kind.attributes'); + return translate.instant('ai-assistant.review.head-change.' + verb, {kind}); + } const type = review.detail === 'alarm-rule' ? 'ALARM_RULE' : review.entityType; const key = 'ai-assistant.review.kind.' + type; const phrase = translate.instant(key); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html index fff54110b0..11489f55ee 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html @@ -6,7 +6,7 @@ -->
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 18465f5a25..210cdbde74 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 @@ -93,7 +93,7 @@ } @else if (msg.from === 'ACTION' && plans[$index]; as plan) {
+ (run)="runPlan.emit({run: $event, steps: plan.steps})" (changeRequested)="changePlan.emit()">
} @else if (msg.from === 'ACTION' && handOvers[$index]; as card) {
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 8680d28d7f..5583c127d2 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 @@ -561,6 +561,10 @@ padding: 0; background: none; box-shadow: none; + font-weight: 400; + } + + td:first-child code.k-ent { font-weight: 500; } 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 6b77a240c7..9540bfc852 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 @@ -508,6 +508,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { this.runningLead = running.length ? running[0] : -1; this.runningCount = running.length; this.findReadGroups(); + const last = this.messages[this.messages.length - 1]; + this.waitApproval = last?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(last as ApprovalChatMessage); if (changes.messages.firstChange) { if (this.initialScroll === 'bottom') { this.pinToBottom(); @@ -521,10 +523,6 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { const prevLastMsg = prevMsgs?.[prevMsgs.length - 1]; const msgs = changes.messages.currentValue as ChatMessage[]; const lastMsg = msgs[msgs.length - 1]; - // In auto-approve we are not blocked on the user, so the assistant keeps working: the - // thinking indicator stays visible (waitApproval false), and the view follows the stream of - // auto-generated cards only while the reader is near the bottom. - this.waitApproval = lastMsg?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(lastMsg as ApprovalChatMessage); if (this.autoApprove) { if (wasNearBottom) { setTimeout(() => this.scrollToBottom('auto'), 0); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html index 01d3972043..35bd1082fd 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html @@ -24,10 +24,7 @@ } @else { @if (renamable()) { + } - + @if (fullscreen() || !headNarrow()) { + + } @if (!fullscreen()) { - } @if (docked() && (split() || splitAvailable())) { @@ -415,9 +419,23 @@ {{ (split() ? 'ai-assistant.back-to-panel' : 'ai-assistant.split-view') | translate }} } - @if (recentChats().length) { -
{{ 'ai-assistant.recent-chats' | translate }}
- @for (other of recentChats(); track other.id) { + @if (chat()) { + + + + } + @for (group of otherChats(); track group.label) { +
{{ group.label | translate }}
+ @for (other of group.chats; track other.id) { - @if (chat()) { - - } 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 72fd4f050f..928d69fb9d 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 @@ -23,6 +23,7 @@ .ai-chat-head { position: relative; + container: k-head / inline-size; flex: none; display: flex; align-items: center; 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 2ef5fab1d3..64371d66ff 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 @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models'; import { getDefaultTimezone } from '@shared/models/time/time.models'; @@ -46,6 +47,7 @@ import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { environment as env } from '@env/environment'; import { ActionNotificationShow } from '@core/notification/notification.actions'; import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { aiChatNameOf } from '@home/components/ai/ai-text'; import { ActionChatMessage, AiStartedFrom, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; import { AiAssistantPromptExample, @@ -110,14 +112,19 @@ interface AiRefusal { '[class.split]': 'split() && docked()', '[class.v-page]': '!docked()', '[class.v-panel]': 'docked()' - } + }, + providers: AI_TOOLTIP_PROVIDERS }) export class AiChatComponent implements OnInit, OnDestroy { private static readonly RESUME_ATTEMPTS = 4; private static readonly RESUME_DELAY_MS = 2000; private static readonly NOTICE_MS = 6000; - private static readonly RECENT_CHATS = 5; + private static readonly MENU_CHATS = 4; + + private static readonly NEW_CHAT_TITLE = 'New chat'; + + private static readonly NARROW_HEAD = 500; @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; @@ -167,10 +174,29 @@ export class AiChatComponent implements OnInit, OnDestroy { {key: 'datasheet', icon: 'attach_file', file: true} ]; - recentChats = computed(() => this.chats.chats() - .filter(chat => chat.id !== this.chatId()) - .sort((a, b) => b.createdTime - a.createdTime) - .slice(0, AiChatComponent.RECENT_CHATS)); + otherChats = computed<{label: string; chats: ChatInfo[]}[]>(() => { + const others = this.chats.chats() + .filter(chat => chat.id !== this.chatId()) + .sort((a, b) => (b.updatedTime ?? b.createdTime) - (a.updatedTime ?? a.createdTime)); + const startedHere = new Set(this.panelService.chatsStartedHere()); + const here = others.filter(chat => startedHere.has(chat.id)).slice(0, AiChatComponent.MENU_CHATS - 1); + const recent = others.filter(chat => !startedHere.has(chat.id)).slice(0, Math.max(1, AiChatComponent.MENU_CHATS - here.length)); + return [ + ...(here.length ? [{label: 'ai-assistant.on-this-page', chats: here}] : []), + ...(recent.length ? [{label: 'ai-assistant.recent-chats', chats: recent}] : []) + ]; + }); + + headNarrow = signal(false); + + shownTitle = computed(() => { + const title = this.chat()?.title; + if (title && title !== AiChatComponent.NEW_CHAT_TITLE) { + return title; + } + const first = this.messages().find(message => message.from === 'USER') as GeneralChatMessage | undefined; + return typeof first?.content === 'string' && first.content.trim() ? aiChatNameOf(first.content) : title; + }); fullscreen = signal(false); @@ -549,6 +575,14 @@ export class AiChatComponent implements OnInit, OnDestroy { }); ngOnInit(): void { + if (typeof ResizeObserver !== 'undefined') { + const head = new ResizeObserver(() => { + const width = this.hostElement.querySelector('.ai-chat-head')?.clientWidth ?? 0; + this.headNarrow.set(width > 0 && width < AiChatComponent.NARROW_HEAD); + }); + head.observe(this.hostElement); + this.destroyRef.onDestroy(() => head.disconnect()); + } this.loadChat$.pipe( switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( catchError(err => { @@ -1054,8 +1088,11 @@ export class AiChatComponent implements OnInit, OnDestroy { this.messageCancelled = false; const startOrContinue$ = this.chatId() ? of(null) - : this.chats.create('New chat', this.newChatAutoApprove()).pipe( + : this.chats.create(AiChatComponent.NEW_CHAT_TITLE, this.newChatAutoApprove()).pipe( tap(chat => { + if (this.variant() === 'panel') { + this.panelService.noteStartedHere(chat.id); + } this.freshChatId = chat.id; this.shownChatId = chat.id; this.chatId.set(chat.id); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html index 4e9c9baef8..26b3ad0bd7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html @@ -7,12 +7,12 @@
@for (option of question().options; track option.label) { } - diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts index d38ab5bd0d..27c16f7082 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts @@ -22,7 +22,6 @@ export class AiColorFieldComponent { question = input.required(); value = model(''); - disabled = input(false); enter = output(); private elementRef: ElementRef = inject(ElementRef); @@ -40,9 +39,6 @@ export class AiColorFieldComponent { } openHex(): void { - if (this.disabled()) { - return; - } if (!this.other()) { this.value.set('#'); } @@ -76,9 +72,6 @@ export class AiColorFieldComponent { } openPicker(picker: HTMLInputElement, field: HTMLInputElement): void { - if (this.disabled()) { - return; - } picker.value = aiHexOf(field.value) ?? '#000000'; try { picker.showPicker(); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts index aba2c626b3..e1915d1162 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts @@ -10,8 +10,8 @@ import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; import { AiFadeInImageDirective } from '@home/components/ai/ai-fade-in-image.directive'; import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; import { AiSevMarkComponent } from '@home/components/ai/ai-sev-mark.component'; -import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; +import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/ai/ai-tooltip'; @NgModule({ declarations: [ @@ -22,12 +22,13 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry AiFadeInImageDirective, AiSpinComponent, AiSevMarkComponent, - AiLoadingModalComponent, AiNoTelemetryModalComponent ], imports: [ CommonModule, - SharedModule + SharedModule, + AiTooltipChainDirective, + AiTipIfCutDirective ], exports: [ AiAssistantButtonComponent, @@ -37,8 +38,9 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry AiFadeInImageDirective, AiSpinComponent, AiSevMarkComponent, - AiLoadingModalComponent, - AiNoTelemetryModalComponent + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective ] }) export class AiCoreModule {} 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 7fb233ca15..3c772e1f21 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 @@ -1,12 +1,25 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +:host { + display: inline-flex; + min-width: 0; +} + .cred { display: inline-flex; align-items: center; gap: 8px; + min-width: 0; + + > :not(.cred-line) { + flex-shrink: 0; + } } .cred-line { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); color: var(--tb-ink-76); white-space: nowrap; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts index d86504ea90..96eb0771b6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts @@ -1,11 +1,9 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { DestroyRef, Injectable } from '@angular/core'; +import { Injectable } from '@angular/core'; import { createDefaultEntityDataPageLink, singleEntityFilterFromDeviceId } from '@shared/models/query/query.models'; -import { AiLoadingModalComponent, AiLoadingModalData } from '@home/components/ai/ai-loading-modal.component'; -import { dashboardGenerateImage, generateDashboardSteps } from '@home/components/ai/ai.models'; -import { finalize } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { map } from 'rxjs/operators'; +import { forkJoin, of } from 'rxjs'; import { AiNoTelemetryModalComponent, AiNoTelemetryModalData @@ -13,21 +11,20 @@ import { import { Operation } from '@shared/models/security.models'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityService } from '@core/http/entity.service'; +import { DeviceService } from '@core/http/device.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { MatDialog } from '@angular/material/dialog'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { DomSanitizer } from '@angular/platform-browser'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { EntityGroupInfo } from '@shared/models/entity-group.models'; interface GenerateDashboardOptions { deviceId: string; - destroyRef?: DestroyRef; - noTelemetry: AiNoTelemetryModalData; - beforeOpen?: () => void; + deviceName?: string; + keys?: string[]; + checkTelemetry?: boolean; + noTelemetry?: AiNoTelemetryModalData; + beforeCompose?: () => void; } interface AllowDashboardGenerateOptions { @@ -41,47 +38,29 @@ interface AllowDashboardGenerateOptions { export class AiDashboardGenerationService { constructor(private entityService: EntityService, + private deviceService: DeviceService, private dialog: MatDialog, - private aiChatService: AiChatService, - private router: Router, + private panelService: AiAssistantPanelService, private translate: TranslateService, - private sanitizer: DomSanitizer, - private store: Store, private userPermissionsService: UserPermissionsService) { } - generateWithTelemetryCheck(opts: GenerateDashboardOptions): void { - this.entityService.findEntityKeysByQueryV2({ + askInChat(opts: GenerateDashboardOptions): void { + const telemetry$ = opts.checkTelemetry === false ? of(true) : this.entityService.findEntityKeysByQueryV2({ entityFilter: singleEntityFilterFromDeviceId(opts.deviceId), pageLink: createDefaultEntityDataPageLink(1), - }, true, false).subscribe((res) => { - opts.beforeOpen?.(); - if (res.timeseries.length) { - this.generate(opts.deviceId, opts.destroyRef); - } else { - this.openNoTelemetryModal(opts.noTelemetry); + }, true, false).pipe(map(res => res.timeseries.length > 0)); + const name$ = opts.deviceName ? of(opts.deviceName) : this.deviceService.getDevice(opts.deviceId, {ignoreLoading: true}).pipe(map(device => device.name)); + forkJoin([telemetry$, name$]).subscribe(([hasTelemetry, name]) => { + if (!hasTelemetry) { + this.openNoTelemetryModal(opts.noTelemetry ?? {}); + return; } - }); - } - - generate(deviceId: string, destroyRef?: DestroyRef, timeseriesKeys: string[] = []): void { - const dialogRef = this.dialog.open(AiLoadingModalComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - messages: generateDashboardSteps, - estimateWaitTime: 60000, - image: dashboardGenerateImage - } as AiLoadingModalData - }); - let request$ = this.aiChatService.generateDashboard(deviceId, timeseriesKeys).pipe( - finalize(() => dialogRef.close()) - ); - if (destroyRef) { - request$ = request$.pipe(takeUntilDestroyed(destroyRef)); - } - request$.subscribe({ - next: (response) => this.router.navigate(['/dashboards', response]) + opts.beforeCompose?.(); + const keys = (opts.keys ?? []).filter(Boolean); + this.panelService.compose(keys.length + ? this.translate.instant('ai-assistant.ask.device-dashboard-keys', {name, keys: keys.join(', ')}) + : this.translate.instant('ai-assistant.ask.device-dashboard', {name})); }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html deleted file mode 100644 index 59a00e96d0..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html +++ /dev/null @@ -1,15 +0,0 @@ - -
-
- Loading -
- {{ statusMessage | translate }} - {{ 'solution-creator.estimate-wait-time' | translate: {time: (data.estimateWaitTime | milliSecondsToTimeString:true : true)} }} -
-
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss deleted file mode 100644 index b0786e00db..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -.tb-generated { - z-index: 3; - .panel { - box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.04), 0 12px 32px 0 rgba(0, 0, 0, 0.08); - background-color: #fff; - width: 500px; - } - img { - width: 200px; - } - .info { - white-space: pre-line; - text-align: center; - line-height: 1.5; - letter-spacing: 0.15px; - } - - .msg.text-changed { - animation: fadeInSlideUp 0.5s ease-out forwards; - } - - @keyframes fadeInSlideUp { - 0% { - opacity: 0; - transform: translateY(15px); - } - 100% { - opacity: 1; - transform: translateY(0); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts deleted file mode 100644 index 3ab1c957eb..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, DestroyRef, Inject, OnInit, ViewEncapsulation } from '@angular/core'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { Router } from '@angular/router'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { from, of } from 'rxjs'; -import { concatMap, delay } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { generatedStateImages } from '@home/components/ai/ai.models'; - -export interface AiLoadingModalData { - messages: Array<{text: string; delay: number}>; - estimateWaitTime: number; - image?: string; -} - -@Component({ - selector: 'tb-ai-loading-modal', - templateUrl: './ai-loading-modal.component.html', - styleUrl: './ai-loading-modal.component.scss', - encapsulation: ViewEncapsulation.None, - standalone: false, - host: { - style: 'width: 100%; height: 100%; min-height: 100%; display: flex; overflow: hidden;' - } -}) -export class AiLoadingModalComponent extends DialogComponent implements OnInit { - - generateImage: string = generatedStateImages[Math.floor(Math.random() * generatedStateImages.length)]; - statusMessage: string = ''; - statusMessageChanged = false; - - constructor(protected store: Store, - protected router: Router, - @Inject(MAT_DIALOG_DATA) public data: AiLoadingModalData, - public dialogRef: MatDialogRef, - private destroyRef: DestroyRef) { - super(store, router, dialogRef); - } - - ngOnInit() { - this.initGenerateState(); - } - - private initGenerateState(): void { - from(this.data.messages).pipe( - concatMap(message => of(message).pipe(delay(message.delay))), - takeUntilDestroyed(this.destroyRef) - ).subscribe((msg) => { - this.statusMessageChanged = true; - this.statusMessage = msg.text; - setTimeout(() => { - this.statusMessageChanged = false; - }, 500); - }); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html index 262b55a238..b2f16d33d2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html @@ -5,16 +5,16 @@ -->
- - @if (question().number?.unit) { {{ question().number.unit }} } -
@if (wrong()) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts index 685fdc4bf0..b7eae1fd27 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts @@ -15,7 +15,6 @@ export class AiNumberFieldComponent { question = input.required(); value = model(''); - disabled = input(false); enter = output(); private translate = inject(TranslateService); @@ -31,9 +30,6 @@ export class AiNumberFieldComponent { } stepBy(field: HTMLInputElement, direction: number): void { - if (this.disabled()) { - return; - } const current = aiReadNumber(field.value, this.locale()); const base = isNaN(current) ? (this.question().number?.suggested ?? 0) : current; const decimals = Math.max(aiStepDecimals(this.step()), isNaN(current) ? 0 : aiStepDecimals(current)); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html index 3cfbfe0da2..e750917182 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html @@ -22,7 +22,7 @@ {{ gate() || !progress() ? ('ai-assistant.plan.steps' | translate: {count: counted()}) : ('ai-assistant.plan.done-of' | translate: {done: done(), count: counted()}) }} @if (gate()) { - @@ -47,7 +47,7 @@ - } @else { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts index 05442d6a15..282a52dd5a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts @@ -30,7 +30,7 @@ export class AiPlanComponent { open = this.fold.open; @Output() run = new EventEmitter(); - @Output() change = new EventEmitter(); + @Output() changeRequested = new EventEmitter(); private cleared = signal>(new Set()); 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 628dd9989f..b01eee5cf8 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 @@ -53,7 +53,7 @@
@if (suggestion && !hasText()) { - + {{ 'ai-assistant.suggestion-sr' | translate: {text: suggestion} }} } @@ -106,7 +106,7 @@ [style.--n]="step.options.length"> @for (option of step.options; track option.label) { @@ -115,7 +115,7 @@ {{ otherLabel(step) }} - @@ -128,11 +128,11 @@ @for (option of step.options; track option.label) { + (click)="pick(step, option.label)">{{ option.label }} }
@@ -142,16 +142,16 @@ @for (option of step.options; track option.label) { + (click)="pick(step, option.label)">{{ option.label }} } + (click)="pickOther(step)">{{ step.other?.label ? step.other.label + '…' : ('ai-assistant.question.other-chip' | translate) }}
@if (isOther(step) && step.number) { - } @else if (isOther(step)) { - @@ -164,7 +164,7 @@ [style.--n]="step.options.length"> @for (option of step.options; track option.label) { @@ -173,7 +173,7 @@ {{ otherLabel(step) }} -