From c5bc6bc17fc734ea6d6e725da14a009a1715d92b Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 3 Dec 2026 11:31:20 +0200 Subject: [PATCH 01/15] Fixed AI chat tooltips not showing and Generate dashboard with AI doing nothing on Home and the AI Assistant page - AI chat tooltips keep Material's own show/hide animations with the scale held at 1, so they fade in at full size and are detached after hiding. - Generate dashboard with AI always starts a new chat; a draft typed in the open chat comes back when that chat is opened again. Where the docked panel can't open (Home, the AI Assistant page), the prompt goes to a new chat on the AI Assistant page. - Keyboard focus shows an AI tooltip at once, also the first time; the tooltip directives use the host object and module declarations. - A new chat's name keeps periods and colons inside words (Sensor v1.2, 192.168.1.10) and underscores inside names. - Alarm lists loaded through /api/alarm and /api/v2/alarms (the Alarms page and entity Alarms tabs) sort severity by priority too; the test also covers text search. - Removed unused code and merged duplicate container queries. --- .../server/dao/sql/alarm/JpaAlarmDao.java | 33 +++++++-- .../server/dao/service/AlarmServiceTest.java | 21 ++++++ .../services/ai-assistant-panel.service.ts | 25 ++++--- .../ai/ai-assistant-panel.component.ts | 73 ++++++++++--------- .../home/components/ai/ai-chat.component.ts | 13 ++++ .../home/components/ai/ai-core.module.ts | 8 +- .../app/modules/home/components/ai/ai-text.ts | 2 +- .../modules/home/components/ai/ai-tooltip.ts | 44 +++++++---- .../pane/solution-installed.component.ts | 8 -- .../ai-assistant/ai-assistant.component.ts | 14 +++- ui-ngx/src/theme/ai-theme.scss | 35 +++------ 11 files changed, 174 insertions(+), 102 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java index 8be5f1ffbb..6d7aa5fb6b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java @@ -12,6 +12,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -145,6 +147,25 @@ public class JpaAlarmDao extends JpaAbstractDao implements A return findByIdAsync(tenantId, key); } + private static final String SEVERITY_PROPERTY = "severity"; + + private static final String SEVERITY_RANK = "(case a.severity" + + Arrays.stream(AlarmSeverity.values()) + .map(severity -> " when " + AlarmSeverity.class.getName() + "." + severity.name() + " then " + severity.ordinal()) + .collect(Collectors.joining()) + + " else " + AlarmSeverity.values().length + " end)"; + + private static Pageable toAlarmPageable(PageLink pageLink) { + Pageable pageable = DaoUtil.toPageable(pageLink); + if (pageable.getSort().getOrderFor(SEVERITY_PROPERTY) == null) { + return pageable; + } + List orders = pageable.getSort().stream() + .map(order -> SEVERITY_PROPERTY.equals(order.getProperty()) ? JpaSort.unsafe(order.getDirection(), SEVERITY_RANK).iterator().next() : order) + .toList(); + return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders)); + } + @Override public PageData findAlarms(TenantId tenantId, AlarmQuery query) { log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink()); @@ -164,7 +185,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -179,7 +200,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -201,7 +222,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -230,7 +251,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -247,7 +268,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -273,7 +294,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } 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 d0c19ec12c..38397e2069 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 @@ -64,6 +64,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.exception.DataValidationException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -834,6 +835,26 @@ public class AlarmServiceTest extends AbstractServiceTest { 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()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + pageLink.setTextSearch("Severity"); + 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()); + + List types = Arrays.stream(AlarmSeverity.values()).map(severity -> "Severity " + severity).toList(); + for (SortOrder.Direction direction : SortOrder.Direction.values()) { + List expected = direction == SortOrder.Direction.ASC ? byPriority : byPriority.reversed(); + TimePageLink timePageLink = new TimePageLink(10, 0, null, new SortOrder("severity", direction), null, null); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .affectedEntityId(device.getId()).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .typeList(types).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarms(tenantId, AlarmQuery.builder() + .affectedEntityId(device.getId()).pageLink(new TimePageLink(10, 0, "Severity", new SortOrder("severity", direction), null, null)).build()) + .getData().stream().map(AlarmInfo::getId).toList()); + } } private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { 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 32d2b7fb33..4e39d0b71d 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 @@ -84,6 +84,9 @@ export class AiAssistantPanelService implements OnDestroy { ).subscribe(event => { const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects); this._suppressed.set(suppressed); + if (suppressed && !AiAssistantPanelService.onAiPage(event.urlAfterRedirects)) { + this._composed.set(null); + } const openHere = this._openOnArrival && !suppressed; if (!suppressed) { this._openOnArrival = false; @@ -128,6 +131,11 @@ export class AiAssistantPanelService implements OnDestroy { this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null); } + private static onAiPage(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/ai-assistant' || path.startsWith('/ai-assistant/'); + } + private static withoutPanel(url: string): boolean { const path = (url || '/').split(/[?#]/)[0]; return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/')); @@ -382,22 +390,19 @@ export class AiAssistantPanelService implements OnDestroy { this._open.set(true); } - private _composed = signal<{text: string; fresh: boolean} | null>(null); + private _composed = signal(null); readonly composed = this._composed.asReadonly(); compose(text: string): void { - if (this._suppressed()) { - return; + this._composed.set(text); + if (!this._suppressed()) { + this.openPanel(); + } else if (!AiAssistantPanelService.onAiPage(this.router.url)) { + this.router.navigateByUrl('/ai-assistant'); } - this._composed.set({text, fresh: !this._open()}); - this.openPanel(); - } - - composesFresh(): boolean { - return !!this._composed()?.fresh; } - takeComposed(): {text: string; fresh: boolean} | null { + takeComposed(): string | null { const composed = this._composed(); this._composed.set(null); return composed; 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 2589bd88cb..fc1b4a479e 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 @@ -99,43 +99,50 @@ export class AiAssistantPanelComponent { onCleanup(() => document.documentElement.classList.remove('tb-ai-docked')); }); + private wasOpen = false; + private openEffect = effect(() => { - if (this.panelService.open()) { - untracked(() => { - if (this.panelService.composesFresh()) { - this.chatId.set(undefined); - this.chats.load().subscribe(); - return; - } - const carried = this.panelService.hasCarriedChat(); - if (!carried) { - this.dropChatFromOtherContext(); - } - this.chats.load().subscribe(() => { - if (carried) { - const chatId = this.panelService.takeCarriedChat(); - if (chatId && this.chats.find(chatId)) { - this.chatId.set(chatId); - return; - } - } - this.selectLastChat(); - }); - }); - } + const open = this.panelService.open(); + const composed = this.panelService.composed(); + untracked(() => { + const opened = open && !this.wasOpen; + this.wasOpen = open; + if (!open) { + return; + } + if (composed) { + this.startComposed(this.panelService.takeComposed(), opened); + } else if (opened) { + this.restoreChat(); + } + }); }); - private composeEffect = effect(() => { - if (this.panelService.composed() && this.panelService.open()) { - untracked(() => { - const composed = this.panelService.takeComposed(); - if (composed.fresh) { - this.chatId.set(undefined); - } - setTimeout(() => this.chat?.composeText(composed.text), AiAssistantPanelComponent.COMPOSE_DELAY_MS); - }); + private startComposed(text: string, opened: boolean): void { + this.chat?.keepDraft(); + this.chatId.set(undefined); + if (opened) { + this.chats.load().subscribe(); } - }); + setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS); + } + + private restoreChat(): void { + const carried = this.panelService.hasCarriedChat(); + if (!carried) { + this.dropChatFromOtherContext(); + } + this.chats.load().subscribe(() => { + if (carried) { + const chatId = this.panelService.takeCarriedChat(); + if (chatId && this.chats.find(chatId)) { + this.chatId.set(chatId); + return; + } + } + this.selectLastChat(); + }); + } private contextSwitchEffect = effect(() => { const key = this.panelService.contextKey(); 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 64371d66ff..a842b04685 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 @@ -530,9 +530,16 @@ export class AiChatComponent implements OnInit, OnDestroy { untracked(() => this.countNewTurns()); }); + private keptDraft: {chatId: string; text: string} | null = null; + private chatIdEffect = effect(() => { const chatId = this.chatId(); untracked(() => { + if (chatId && this.keptDraft?.chatId === chatId) { + const draft = this.keptDraft.text; + this.keptDraft = null; + setTimeout(() => this.promptInput?.setValue(draft)); + } if (this.fileChat !== chatId) { this.shownFile.set(null); this.fileOpen.set(false); @@ -635,6 +642,12 @@ export class AiChatComponent implements OnInit, OnDestroy { setTimeout(() => this.focus()); } + keepDraft(): void { + const chatId = this.chatId(); + const draft = this.promptInput?.message.value ?? ''; + this.keptDraft = chatId && draft.trim() ? {chatId, text: draft} : null; + } + composeText(text: string): void { this.promptInput?.setValue(text); setTimeout(() => this.focus()); 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 e1915d1162..3c15a3f45d 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 @@ -22,13 +22,13 @@ import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/a AiFadeInImageDirective, AiSpinComponent, AiSevMarkComponent, - AiNoTelemetryModalComponent + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective ], imports: [ CommonModule, - SharedModule, - AiTooltipChainDirective, - AiTipIfCutDirective + SharedModule ], exports: [ AiAssistantButtonComponent, diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-text.ts b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts index c3961de26b..fadd7049b7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-text.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts @@ -21,7 +21,7 @@ const CHAT_NAME_MAX = 44; const CHAT_NAME_MIN_CUT = 20; export function aiChatNameOf(prompt: string): string { - const first = prompt.replace(/[*_`#>]/g, '').trim().split(/[.:\n]/)[0].trim(); + const first = prompt.replace(/[*`#>]|(?>(ElementRef); + private inChat = inject(MAT_TOOLTIP_DEFAULT_OPTIONS, {optional: true}) === AI_TOOLTIP_OPTIONS; - @HostListener('mouseenter') onEnter(): void { - if (this.inChat()) { + if (this.inChat) { this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay; } } - @HostListener('mouseleave') onLeave(): void { - if (this.inChat() && this.tooltip._isTooltipVisible()) { + if (this.inChat && this.tooltip._isTooltipVisible()) { lastTipAt = Date.now(); } } - @HostListener('focus') onFocus(): void { - if (this.inChat()) { - this.tooltip.showDelay = this.host.nativeElement.matches(':focus-visible') ? 0 : AI_TOOLTIP_OPTIONS.showDelay; + if (this.inChat && !this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); } } - - private inChat(): boolean { - return (this.tooltip.tooltipClass as string | string[]) === AI_TOOLTIP_OPTIONS.tooltipClass; - } } @Directive({ selector: '[aiTipIfCut]', - standalone: true + standalone: false, + host: { + '(mouseenter)': 'check()', + '(focus)': 'onFocus()' + } }) export class AiTipIfCutDirective { private tooltip = inject(MatTooltip, {self: true}); private host = inject>(ElementRef); - @HostListener('mouseenter') - @HostListener('focus') check(): void { const element = this.host.nativeElement.querySelector('.tb-ai-cut') ?? this.host.nativeElement; this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1; } + + onFocus(): void { + this.check(); + if (!this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); + } + } } 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 index 8153a44b15..f6eab7816e 100644 --- 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 @@ -303,10 +303,6 @@ export class SolutionInstalledComponent { return (severity ?? '').toLowerCase(); } - dashboardUser(row: AggregatedEntityResult): string { - return this.userName(row.primary?.additionalData?.userId); - } - canViewAs(row: AggregatedEntityResult): boolean { return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR; } @@ -319,10 +315,6 @@ export class SolutionInstalledComponent { 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/pages/ai-assistant/ai-assistant.component.ts b/ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts index dde6295b0e..0600da8a90 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 @@ -217,6 +217,18 @@ export class AiAssistantComponent implements OnInit, OnDestroy { } }); + private composeEffect = effect(() => { + const composed = this.panelService.composed(); + if (composed && this.ready() && this.panelService.suppressed()) { + untracked(() => { + const text = this.panelService.takeComposed(); + this.chat?.keepDraft(); + this.newChat(); + setTimeout(() => this.chat?.composeText(text)); + }); + } + }); + private listEdgesEffect = effect(() => { this.groups(); setTimeout(() => this.listEdges()); @@ -267,7 +279,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy { next: ([, chats]) => { const params = this.route.snapshot.queryParamMap; const handOff = this.panelService.takeHandOff(); - const first = !handOff && !params.get('chatId') && !params.get('solutionId') && !chats.length; + const first = !handOff && !this.panelService.composed() && !params.get('chatId') && !params.get('solutionId') && !chats.length; this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats, first || params.get('getStarted') === 'true', params.get('cli') === 'true'); this.ready.set(true); diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 9f3be8d762..2152e9c46f 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -475,31 +475,22 @@ } } -@keyframes tb-ai-tip-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} - -@keyframes tb-ai-tip-out { - from { - opacity: 1; - } - to { - opacity: 0; - } -} - .mat-mdc-tooltip.tb-ai-tip { + opacity: 0; + transform: scale(1) !important; + &.mat-mdc-tooltip-show { - animation: tb-ai-tip-in 100ms ease-out forwards; + animation-duration: 100ms; + animation-timing-function: ease-out; } &.mat-mdc-tooltip-hide { - animation: tb-ai-tip-out 60ms ease-in forwards; + animation-duration: 60ms; + animation-timing-function: ease-in; + } + + &._mat-animation-noopable.mat-mdc-tooltip-show { + opacity: 1; } } @@ -2263,9 +2254,7 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); } width: 56px; } } -} -@container k-chat (max-width: 560px) { .k-fields { grid-template-columns: minmax(0, 1fr); gap: 1px 0; @@ -4230,7 +4219,7 @@ cursor: pointer; vertical-align: 1px; } -.composer-ghost-end { + .composer-ghost-end { white-space: nowrap; } From 284907c300aa05384e16a3ecbc2dd5bba817fd6f Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 3 Dec 2026 12:27:53 +0200 Subject: [PATCH 02/15] Fixed the docked AI panel not appearing after a user switch without a page reload (e.g. Login as from the system administrator): AI availability now follows the auth state, and the panel is mounted again when its host comes back --- .../src/app/modules/home/home.component.html | 2 +- ui-ngx/src/app/modules/home/home.component.ts | 21 ++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index e4a2d3177a..c7626e2a10 100644 --- a/ui-ngx/src/app/modules/home/home.component.html +++ b/ui-ngx/src/app/modules/home/home.component.html @@ -118,7 +118,7 @@ - @if (aiAvailable) { + @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 0bee0037c9..8577aa4968 100644 --- a/ui-ngx/src/app/modules/home/home.component.ts +++ b/ui-ngx/src/app/modules/home/home.component.ts @@ -4,12 +4,13 @@ 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 { toSignal } from '@angular/core/rxjs-interop'; import { debounceTime, distinctUntilChanged, map, share, take, takeUntil } from 'rxjs/operators'; import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; import { PageComponent } from '@shared/components/page.component'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState, selectUserSettingsProperty } from '@core/auth/auth.selectors'; +import { getCurrentAuthState, selectAuth, selectUserSettingsProperty } from '@core/auth/auth.selectors'; import { MediaBreakpoints } from '@shared/models/constants'; import screenfull from 'screenfull'; import { MatSidenav } from '@angular/material/sidenav'; @@ -74,17 +75,27 @@ export class HomeComponent extends PageComponent implements AfterViewInit, OnIni private tourService = inject(TourService); - readonly aiAvailable = this.tourService.aiAvailable(); + readonly aiAvailable = toSignal(inject(Store).select(selectAuth).pipe( + map(() => this.tourService.aiAvailable()), + distinctUntilChanged() + ), {initialValue: this.tourService.aiAvailable()}); readonly aiPanelLoaded = signal(false); private injector = inject(Injector); - @ViewChild('aiPanelHost', {read: ViewContainerRef}) set aiPanelHost(host: ViewContainerRef) { - if (host && !this.aiPanelLoaded()) { + private panelHost: ViewContainerRef | undefined; + + @ViewChild('aiPanelHost', {read: ViewContainerRef}) set aiPanelHost(host: ViewContainerRef | undefined) { + this.panelHost = host; + if (!host) { + this.aiPanelLoaded.set(false); + return; + } + if (!this.aiPanelLoaded()) { Promise.all([import('@home/components/ai/ai.module'), import('@home/components/ai/ai-assistant-panel.component')]) .then(([{AiModule}, {AiAssistantPanelComponent}]) => { - if (!this.aiPanelLoaded()) { + if (this.panelHost === host && !this.aiPanelLoaded()) { host.createComponent(AiAssistantPanelComponent, {ngModuleRef: createNgModule(AiModule, this.injector)}); this.aiPanelLoaded.set(true); } From 356e73b9e874677cfd044109fb13564e975705a0 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Thu, 3 Dec 2026 12:39:46 +0200 Subject: [PATCH 03/15] Fixed the AI Assistant button missing from the header after Login as from the system administrator until another page was opened: AI availability is one signal in UserPermissionsService that follows the auth state, read by the header button, the docked panel host and the tour --- .../app/core/http/user-permissions.service.ts | 12 +++++++++--- ui-ngx/src/app/core/services/tour.service.ts | 2 +- .../ai/ai-assistant-button.component.ts | 17 ++++++++++------- ui-ngx/src/app/modules/home/home.component.ts | 9 +++------ 4 files changed, 23 insertions(+), 17 deletions(-) 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 d31ddfe2b4..6504cbf561 100644 --- a/ui-ngx/src/app/core/http/user-permissions.service.ts +++ b/ui-ngx/src/app/core/http/user-permissions.service.ts @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; -import { tap } from 'rxjs/operators'; +import { distinctUntilChanged, map, tap } from 'rxjs/operators'; import { AllowedPermissionsInfo, groupResourceByGroupType, @@ -19,7 +20,7 @@ import { isArray } from '@core/utils'; import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { getCurrentAuthState, selectAuth } from '@core/auth/auth.selectors'; import { Authority } from '@shared/models/authority.enum'; @Injectable({ @@ -35,6 +36,11 @@ export class UserPermissionsService { private userPermissions: MergedUserPermissions; private userOwnerId: EntityId; + readonly aiAvailable = toSignal(inject(Store).select(selectAuth).pipe( + map(() => this.isAiAvailable()), + distinctUntilChanged() + ), {initialValue: false}); + constructor( private http: HttpClient, private store: Store diff --git a/ui-ngx/src/app/core/services/tour.service.ts b/ui-ngx/src/app/core/services/tour.service.ts index 5e6b27768a..5d59332a92 100644 --- a/ui-ngx/src/app/core/services/tour.service.ts +++ b/ui-ngx/src/app/core/services/tour.service.ts @@ -32,7 +32,7 @@ export class TourService { private offered = false; aiAvailable(): boolean { - return this.userPermissions.isAiAvailable(); + return this.userPermissions.aiAvailable(); } offerWelcome(): void { 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 index 7376bd7717..0b2439f73e 100644 --- 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 @@ -41,7 +41,7 @@ const intro: { owner: AiAssistantButtonComponent | null } = {owner: null}; @Component({ selector: 'tb-ai-assistant-button', template: ` - @if (available && !panelService.open() && !panelService.suppressed()) { + @if (available() && !panelService.open() && !panelService.suppressed()) { @let status = cue(); } + } @else if (unchanged.length) { +
+
+ @for (same of unchanged; track $index) { +
+
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }
+
{{ same.value }}
+
+ } +
+
}